1. Function 합성
- Function 합성에서는 아래와 같이 defaul과 static이 정의되어 있다.
(1) default <V> Function<T,V> andThen (Function <? super R, ? exteds V> after)
: 만약 함수 f,g가 있을 때, f.andThen(g)는 f를 먼저 적용 후, 그 다음에 g를 적용한다.
(2) default <V> Function<V,R> compose (Function <? super V, ? exteds T> before)
: 만약 함수 f,g가 있을 때, f.compose(g)는 반대로 g 먼저 적용 후, 그 다음에 f를 적용한다.
(3) static <T> Function<T,T> identify()
: 함수를 적용하기 이전과 이후가 동일한 '항등 함수'가 필요할 때 사용한다.
( (1)과 (2)에서는 예를 들어, 문자열을 숫자로 변경하는 함수 f와 숫자를 2진 문자열로 변환하는 함수 g가
있으면 둘을 결합하여 사용할 수 있다. )
( (3)은 함수에 x를 대입하면 결과가 x인 함수라서, 잘 사용하지 않는다. 나중에 map()으로 변환 작업을 할 때,
변함 없이 처리하고자 할 때 사용된다. )
( 아래의 각 예시 코드를 보고 이해하자. )
(1) f.andThen(g)
Function<String, Integer> f = (s) -> Integer.parseInt(s, 16);
Function<Integer, String> g = (i) -> Integer.toBinaryString(i);
Function<String, String> h = f.andThen(g);
System.out.println(h.apply("FF"));
(2) f.compose(g)
Function<Integer, String> g = (i) -> Integer.toBinaryString(i);
Function<String, Integer> f = (s) -> Integer.parseInt(s, 16);
Function<Integer, Integer> h = f.compose(g);
System.out.println(h.apply(2));
(3) f(x) = x
Function<String, String> f = x -> x;
//또는 Function<String, String> f = Function.indentity();
System.out.println(f.apply("AAA"));
//AAA가 그대로 출력됨.
2. Predicate의 결합
- 여러 조건식을 논리 연산자인 &&, ||, !과 같이 연결해서 하나의 식을 구성할 수 있는 것처럼,
여러 Predicate를 and(), or(), negate()로 연결해서 하나의 새로운 식을 구성할 수 있다.
아래의 코드를 보자.
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
Predicate<Integer> all = notP.and(q.or(r));
// 100 <= i &&(i<200 || i%2 == 0)
System.out.println(all.test(150));
// true
- static 메서드인 isEqual()은 두 대상을 비교하는 Predicate를 만들 때 사용한다.
먼저, isEqual()의 매개변수로 비교대상을 하나 지정하고, 또 다른 비교대상은 test()의
매개변수로 지정한다.
Predicate<String> p = Predicate.isEqual(str1);
boolean result = p.test(str2);
//str1과 str2가 같은지 비교하여 결과를 반환한다.
또는
boolean result = Predicate.isEqual(str1).test(str2);
3. Function의 합성과 Predicate의 결합을 이해하기 위한 예제(1)
: 위에서 했던 예제를 하나로 모은 예제이다.
'자바 > 람다식' 카테고리의 다른 글
메서드 참조 (0) | 2022.04.12 |
---|---|
java.util.function 패키지 (0) | 2022.04.11 |
함수형 인터페이스 (0) | 2022.04.11 |
람다식의 기본 개념 (0) | 2022.04.11 |