Unfazed❗️🎯

Predicate의 결합 본문

Java

Predicate의 결합

9taetae9 2023. 10. 6. 21:33
728x90

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); // 100 <= i && i < 200 || i%2 == 0

Predicate<Integer> all2 = notP.and(q.or(r)); // 100 <= i && (i < 200 || i%2==0)

 

System.out.println(all.test(2)); // true

System.out.println(all2.test(2)); // false  

 

-등가비교를 위한 Predicate의 작성에는 isEqual()를 사용(static 메서드)

boolean result = Predicate.isEqual(str1).test(str2);  // str1.equals(str2);

 

public static void main(String[] args) {

Function<String, Integer> f = (s) -> Integer.parseInt(s, 16);

Function<Integer, String> g = (i) -> Integer.toBinaryString(i);

 

Function<String, String> h = f.andThen(g);

Function<Integer, Integer> h2 = f.compose(g);

 

System.out.println(h.apply("FF")); //"FF" -> 255 -> "11111111"

System.out.println(h2.apply(2)); //2 -> "10" -> 16

 

Function<String, String> f2 = x->x; //항등 함수 (identity function)

System.out.println(f2.apply("AAA")); //AAA가 그대로 출려됨

 

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)

System.out.println(all.test(150)); //true

 

String str1="abc";

String str2="abc";

 

//str1과 str2가 같은지 비교한 결과를 반환

Predicate<String> p2 = Predicate.isEqual(str1);

//boolean result = str1.equals(str2);

boolean result = p2.test(str2);

System.out.println(result);

 

 

}

 

output:

11111111

16

AAA

true

true

728x90