gwooden_코린이
java_andThen/compose_221205(11일차) 본문
728x90
인터페이스 {
추상메서드;
default 메서드
}
default 메서드
andThen(), compose()
Consumer, Function, Operatro 3개만 존재
composer()
Function<T, R>, DoubleUnaryOperator, IntUnaryOperator, LongUnaryOperator
람다식을 묶어서 한번에 사용하기 좋음
1. andThen
- 기본형식
인터페이스AB = 인터페이스A.andThen(인터페이스B);
최종결과 = 인터페이스AB.method();
andThen은 첫 번째 인터페이스가 먼저 실행된다.
인터페이스AB.method() -> 인터페이스A(람다) -> 인터페이스B(람다) -> 최종결과 리턴
package andThen;
import java.util.function.Consumer;
public class Main {
public static void main(String[] args) {
//Consumer는 리턴이 없음
Consumer<Member> conA = (x) -> {
System.out.println("conA : " + x.getName());
};
Consumer<Member> conB = (x) -> {
System.out.println("conB : " + x.getId());
};
Consumer<Member> conAB = conA.andThen(conB);
conAB.accept(new Member("홍길동", "hong"));
}
}
2.compose
- 기본형식
인터페이스AB = 인터페이스A.compose(인터페이스B);
최종결과 = 인터페이스AB.method();
compose는 두 번째 인터페이스가 먼저 실행된다.
인터페이스AB.method() -> 인터페이스B(람다) -> 인터페이스A(람다) -> 최종결과 리턴
package andThen;
import java.util.function.Function;
public class Main02 {
public static void main(String[] args) {
Function<Integer, Integer> conA = (x) -> {
return x * 10;
};
Function<Integer, Integer> conB = (x) -> {
return x - 5;
};
Function<Integer, Integer> conAB = conA.compose(conB);
int result = conAB.apply(10);
System.out.println("compase : " + result);
}
}
package andThen;
import java.util.function.Function;
public class Main02 {
public static void main(String[] args) {
Function<Integer, Integer> conA = (x) -> {
return x * 10;
};
Function<Integer, Integer> conB = (x) -> {
return x - 5;
};
Function<Integer, Integer> conAB = conA.compose(conB);
int result = conAB.apply(10);
System.out.println("compase : " + result);
conAB = conA.andThen(conB);
result = conAB.apply(10);
System.out.println("andThen : " + result);
}
}
728x90
'java > 11일차' 카테고리의 다른 글
java_스트림_221205(11일차) (0) | 2022.12.05 |
---|---|
java_Predicate_221205(11일차) (0) | 2022.12.05 |
java_Operator(오퍼레이터)_221205(11일차) (0) | 2022.12.05 |
Comments