JAVA day 13

lee·2021년 12월 15일
0

JAVA

목록 보기
13/14

learning

수업내용 링크

저장소 : GitHub Repositories leeconomy1121/java-study

람다식(Lamdba Expressions)

  • 함수형 인터페이스(Functional Interface)
    기본 함수형 인터페이스
    자바에서 기본적으로 제공하는 함수형 인터페이스는 다음과 같은 것들이 있습니다.
    Runnable
    Supplier
    Conusumer
    Function<T, R>
    Predicate
    이 외에도 다양한 것들이 있습니다. 자바의 java.util.function 패키지의 정의 되어 있으니 더 많은 것을 확인 할 수 있습니다.

App class

package lambda_example;

interface Runner {
	void execute(); // 추상 메소드 1개 => 람다식 사용가능
}

public class App2 {

	public static void main(String[] args) {
		Runner run = () -> System.out.println("헬로우");
		// 실행 코드가 한 줄일 때 코드블록{} 생략 가능
		run.execute();
		
		System.out.println(run instanceof Runner); // run은 Runner의 객체인가? (true)
		System.out.println(run.getClass());        // 클래스는 람다식
	}

}

📝결과

  • 매개변수 (Parameter)

App class

package lambda_parameter;

interface Runner {
	void excute(String t); // 추상 메소드에 매개변수가 있는 경우
}

public class App {

	public static void main(String[] args) {
		// 매개변수가 있는 경우
		Runner run1 = (s) -> System.out.println(s);
		run1.excute("펭수");
		
		Runner run2 = x -> System.out.println(x); // 매개변수 1개일 때 () 생략 가능, 매개변수가 없을 떄는 ()
		run2.excute("길동");

	}

}
  • 람다식 리턴

App class

package lambda_return;

interface Joiner {
	String join(String text1, String text2); // 추상 메소드에 리턴, 매개변수 있는 경우
}

public class App {
	public static void main(String[] args) {
		// 리턴값이 있는 경우
		Joiner joiner = (t1, t2) -> {
			String text = t1 + " - "+ t2;
			return text;
		};
		
		System.out.println(joiner.join("치킨", "맥주"));
		System.out.println(joiner.join("학원", "공부"));
		
		Joiner joiner2 = (s1, s2) -> s1 + " + " + s2; // 코드가 한 줄일 때 return도 생략 가능
		
		System.out.println(joiner2.join("치킨", "맥주"));
		System.out.println(joiner2.join("학원", "공부"));
	}

}

📝결과

  • Predicate
    Predicate는 Type T 인자를 받고 boolean을 리턴하는 함수형 인터페이스입니다.

App class

package lambda_interface;

import java.util.function.Predicate;

public class App {

	public static void main(String[] args) {
		// Predicate를 사용
		Predicate<String> p1 = new Predicate<String>() {
			public boolean test(String t) {
				// 입력된 타입의 객체를 검사해서 참, 거짓으로 리턴				
				return t.length() < 4;
			}
		};
		
		System.out.println(p1.test("abcd"));
		System.out.println(p1.test("하나둘"));
		
		Predicate<String> p2 = t -> t.length() < 4;
		
		System.out.println(p2.test("abcd"));
		System.out.println(p2.test("하나둘"));
		
	}

}

📝결과

  • removeIf(Predicate), replaceAll(UnaryOperator)
    removeIf : 배열을 순회하면서 조건에 따른 삭제
    replaceAll : 배열을 순회하면서 요소값을 변환

App class

package exercise;

import java.util.ArrayList;
import java.util.List;

public class App {

	public static void main(String[] args) {
		// 연습문제
		List<Integer> list = new ArrayList<>();
		list.add(1);
		list.add(5);
		list.add(9);
		list.add(1000);
		list.add(3);
		list.add(6);
		list.add(-20);
		list.add(4);
		
		list.removeIf(n -> n < 0 || n > 10);
		list.replaceAll(n -> n + 100);
		list.forEach(r -> System.out.println(r));

	}

}

📝결과

  • 멀티쓰레드(multiThread)
    synchronized : 멀티쓰레드 환경에서 두개 이상의 쓰레드가 하나의 변수에 동시에 접근을 할 때 Race condition(경쟁상태)이 발생하지 않도록 함.

App class

package multiThread3;

public class App {
	
	private int value = 0;
	
	private synchronized void increment() { // 이 메소드는 한번에 하나의 쓰레드만 접근
		value++;
	}

	public void run() throws InterruptedException {
		Runnable runnable = () -> {
			for(int i = 0; i < 10000; i++) {
				increment(); // value를 1씩 증가
			}
		};
		
		Thread t1 = new Thread(runnable); // 새 쓰레드 t1 생성
		Thread t2 = new Thread(runnable); // 새 쓰레드 t2 생성
		Thread t3 = new Thread(runnable); // 새 쓰레드 t3 생성
		
		t1.start(); // t1 실행
		t2.start(); // t2 실행
		t3.start(); // t2 실행
		
//		System.out.println("Value: " + value); // 메인 쓰레드 실행
		
		t1.join(); // 메인 쓰레드가 t1을 실행할 때까지 대기
		t2.join(); // 메인 쓰레드가 t2을 실행할 때까지 대기
		t3.join(); // 메인 쓰레드가 t3을 실행할 때까지 대기
		
		System.out.println("Value: " + value); // t1, t2가 끝난 다음에 출력
		
	}

	public static void main(String[] args) throws InterruptedException {
		// 멀티 쓰레드
		new App().run(); // App 객체를 만들고 run() 메소드 실행
	}

}

📝결과

메소드 레퍼런스(Method Reference)

메소드 레퍼런스(Method Reference) : 람다 표현식을 더 간단하게 표현하는 방법

App class

package example;

import java.util.ArrayList;
import java.util.List;

public class App3 {

	public static void main(String[] args) {
		List<Integer> numbers = new ArrayList<>();
		numbers.add(1);
		numbers.add(6);
		numbers.add(4);
		numbers.add(7);
		numbers.add(3);
		numbers.add(6);
		numbers.add(3);
		
//		numbers.removeIf(n -> n < 5);
//		numbers.replaceAll(n -> n * 2);
		
		numbers.removeIf(App3::filter);
		numbers.replaceAll(App3::map);
		
		numbers.forEach(System.out::println);

	}
	
	private static boolean filter(int n) {
		return n < 5;
	}
	
	private static int map(int n) {
		return n * 2;
	}

}

📝결과

profile
Hello, world!

0개의 댓글