일상기록
Java - Function의 합성, Predicate의 결합 본문
Function의 합성과 Predicate의 결합
java.util.function패키지의 함수형 인터페이스에는 추상메소드 외에도 디폴트 메서드와 static 메소드가 정의되어 있다. Function과 Predicated에 정의된 메소드에 대해서 알아보자 이 두 함수형 인터페이스만 보면 다른 함수형 인터페이스의 메소드도 충분히 응용가능 하다.
Function
default <V> Function<T, V> andThen(Function<? super R, ? extends V> after)
default <V> Function<V, R> compose(Function<? super V, ? extends R> before)
// 원래 Function인터페이스는 반드시 두개의 타입을 지정해야 하므로 두 타입이 같아도 Function<T>라고 쓸 수 없다.
static <T> Function<T, T> identity()
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)
Function의 합성
두 함수의 합성은 어느 함수를 먼저 적용하느냐에 따라 달라진다. 함수 f, g가 있을 때, f.andThen(g)는 함수 f를 먼저 적용하고, 그 다음 함수에 g를 적용한다. f.compose(g)는 반대로 g를 먼저 적용하고 f를 적용한다.
함수 f와 숫자를 2진 문자열로 변환하는 함수 g를 andThen()으로 합성하여 새로운 함수 h를 만들수 있다.
// andThen() 사용예시
Function<String, String> f = (s) -> Integer.parseInt(s, 16);
Function<Integer, String> g = (i) -> Integer.toBinaryString(i);
Function<String, String> h = f.andThen(g);
다음으로 compose()를 이용해서 두 함수를 역순으로 합성하면
// compose() 사용예시
Function<Integer, String> g = (i) -> Integer.toBinaryString(i);
Function<String, Integer> f = (s) -> Integer.parseInt(s, 16);
Function<Integer, Integer> h = f.compose(g);
idnetity()는 함수를 적용하기 이전과 이후가 동일한 '항등 함수'가 필요할 때 사용한다. 이 함수를 람다식으로 표현하면 'x->x'이다.
즉, f(x)=x를 의미한다.
// identity() 사용예시
Function<Integer, String> f = x -> x
// Function<String, String> f = Function.identity(); // 위 문장과 동일
System.out.println(f.apply("AAA")); // AAA가 그대로 출력
항등 함수는 잘 사용되지 않는 편이며 map()으로 변환작업시, 변환없이 그대로 처리하고자 할 때 사용
Predicate의 결합
여러 조건식을 논리 연산자인 &&(and), ||(or), !(not)으로 연결해서 하나의 식을 구성할 수 있는 것처럼, 여러 Predicate를 and(), or(), negate()로 연결해서 하나의 새로운 Predicate로 결합할 수 있다.
Predicate<Integer> p = i -> i < 100;
Predicate<Integer> q = i -> i <200;
Predicate<Integer> r = i -> 1%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
// 직접 넣어줘도 된다
Predicate<Integer> all = notP.and(i -> i < 200).or(i -> i % 2 == 0);
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);
'Java' 카테고리의 다른 글
Java - 스트림(stream) (0) | 2023.04.19 |
---|---|
Java - 메소드 참조 (0) | 2023.04.19 |
java.util.function패키지 (0) | 2023.04.18 |
Java - 람다식(Lambda expression) (1) | 2023.04.18 |
Java - 열거형(Enums) (0) | 2023.04.18 |