14-9~12 Predicate의 결합. CF와 함수형 인터페이스

oyeon·2021년 3월 22일
0

Java 개념

목록 보기
63/70

(인터페이스는 추상 메서드, 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문 돌리던 컬렉션 프레임워크 코드를 아주 간단히 대체할 수 있음

profile
Enjoy to study

0개의 댓글