[Java] Lambda - Predicate의 결합, 메서드 참조

eeminsu·2021년 12월 14일
0
post-thumbnail

자바의 정석을 통해 공부한 내용을 요약하였습니다.

1. Predicate의 결합

default Predicate<T> and(Predicate<? super T> other)
default Predicate<T> or(Predicate<? super T> other)
default Predicate<T> negate()
static<T> Predicate<T> isEqual(Object targetRef)

여러 Predicate를 and(), or(), negate()로 연결해서 새로운 Predicate로 결합할 수 있다.

Predicate<Integer> p = i -> i < 100;
Predicate<Integer> q = i -> i < 200;
Predicate<Integer> r = i -> i%2 == 0;
Predicate<Integer> notP = p.negate(); // i >= 100

// 100 <= i && (i < 200 || i%2 == 0)
Predicate<Integer> all = notP.and(q.or(r));
System.out.println(all.test(150));

isEqual()은 두 대상을 비교하는 Predicate를 만들 때 사용한다.
isEqual()의 매개변수로 비교대상을 하나 지정하고, 다른 비교대상은 test()의 매개변수로 지정한다.

Predicate<String> p = Predicate.isEqual(str1);
boolean result = p.test(str2);

// 위 코드를 아래처럼 합칠 수 있다.
boolean result = Predicate.isEqual(str1).test(str2);



2. 메서드 참조

Function<String, Integer> f = (String s) -> Integer.parseInt(s);

Function<String, Integer> f = Integer::parseInt;

람다식이 하나의 메서드만 호출하는 경우 메서드 참조(Method reference)를 통해 간략히 할 수 있다.

메서드 참조 종류


하나의 메서드만 호출하는 람다식은 '클래스 이름::메서드 이름' 또는 '참조 변수::메서드 이름'으로 바꿀 수 있다.

생성자의 메서드 참조

Supplier<MyClass> s = () -> new MyClass(); //람다식
Supplier<MyClass> s = MyClass::new; // 메서드 참조

Function<Integer, MyClass> s = (i) -> new MyClass(i); //람다식
Function<Integer, MyClass> s = MyClass::new // 메서드 참조

Function<Integer, int[]> f = (i) -> new int[i]; //람다식
Function<Integer, int[]> f = int[]::new; // 메서드 참조
profile
안되면 될 때까지

0개의 댓글