14-9~12 Predicate의 결합. CF와 함수형 인터페이스
(인터페이스는 추상 메서드, default 메서드(JDK 1.8~), static 메서드(JDK 1.8~)를 가질 수 있다.)
Predicate의 결합
- and(), or(), negate()로 두 Predicate를 하나로 결합(default 메서드)
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); // i >= 100 && i < 200 || i % 2 == 0
Predicate<Integer> all2 = notP.and(q.or(r)); // i >= 100 && (i < 200 || i % 2 == 0)
System.out.println(all.test(2)); // true
System.out.println(all2.test(2)); // false
- 등가비교를 위한 Predicate의 작성에는 isEqual()를 사용(static 메서드)
Predicate<String> p = Predicate.isEquals(str1); // isEquals()은 static 메서드
Boolean result = p.test(str2); // str1과 str2 같은지 비교한 결과를 반환
위 두 문장을 아래와 같이 한 문장으로 표현 가능하다.
boolean result = Predicate.isEqual(str1).test(str2);
- andThen : 두 개의 함수 잇기
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")); // "FF" -> 255 -> "11111111"
컬렉션 프레임워크와 함수형 인터페이스
- 함수형 인터페이스를 사용하는 컬렉션 프레임워크의 메서드
list.forEach(i->System.out.print(i + ", "); // list의 모든 요소 추력
list.removeIf(x -> x % 2 == 0 || x % 3 == 0); // 2 또는 3의 배수를 제거
list.replaceAll(i -> i * 10); // 모든 요소에 10을 곱함
// map의 모든 요소를 {k, v}의 형식으로 출력
map.forEach((k, v) -> System.out.print("{"+k+", "+v+"}, "));
forEach로 예전에 Iterator로 while문 돌리던 컬렉션 프레임워크 코드를 아주 간단히 대체할 수 있음
Author And Source
이 문제에 관하여(14-9~12 Predicate의 결합. CF와 함수형 인터페이스), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@oyeon/14-912-Predicate의-결합.-CF와-함수형-인터페이스저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)