chapter3 - 람다 표현식
3.8 람다 표현식을 조합할 수 있는 유용한 메서드
3.8.1 Comparator 조합
- 오름차순
Comparator<Apple> c = Comparator.comparing(Apple::getWeight); - 내림차순
Inventory.sort(comparing(Apple::getWeight).reversed());
3.8.2 Predicate 조합
- 기존 Predicate 반전하는 Predicate 생성 : 빨간 사과가 아닌것.
Predicate<Apple> notRedApplePredicate = redApplePredicate.negate(); - 두 Predicate 조합 : 빨란 사과이면서, 150보다 무거운 사과.
Predicate<Apple> redAndHeavyApple = redApple.and( a->a.getWeight() > 150 ); - or : 빨간색이면서 150보다 무거운 사과 거나, 그냥 녹색 사과
Predicate<Apple> redAndHeavyAppleOrGreen = redApple.and( a -> a.getWeight() > 150 ) .or( a -> "green".equals(a.getColor()) );
3.8.3 Function 조합
- andThen : 주어진 함수를 먼저 적용한 결과를 다른 함수의 입력으로 전달하는 함수를 반환한다.
Function<Integer,Integer> f = x -> x + 1; //f함수에서 계산된 결과 값을 a라고 할때, Function<Integer,Integer> g = x -> x * 1; // 해당 결과값 a를 g함수에 f에 적용할수 있다. Function<Integer,Integer> h = f.andThen(g); //f의 결과 값을 g값에 인자값으로 넘긴다. int result = h.apply(1); // = g(f(x))= g(f(1)) = 4 - compose : andThen의 반대
Function<Integer,Integer> f = x -> x + 1; Function<Integer,Integer> g = x -> x * 1; Function<Integer,Integer> h = f.compose(g); //g의 결과 값을 f에 인자값으로 넘긴다. int result = h.apply(1); // = f(g(x)) = f(g(1)) = 3