Predicate
-
CS) Function,Predicate2023.02.08
CS) Function,Predicate
2023. 2. 8. 18:16
- Function 과 Predicate에 정의된 메서드를 알아본다.
Function에 정의된 메서드
test(T t), andThen(), compose(), identity()
test(T t) -> Function에 존재하는 abstract method로 하나의 argument 를 받아 boolean을 return해준다.
Function<Integer, Integer> f1 = x -> x + 1;
Function<Integer, Integer> f2 = x -> x * 2;
// Apply f2 after f1
Function<Integer, Integer> f4 = f1.andThen(f2);
System.out.println(f4.apply(2)); // Outputs 6
// Compose f2 before f1
Function<Integer, Integer> f3 = f1.compose(f2);
System.out.println(f3.apply(2)); // Outputs 5
위 코드에서 f1.andThen(f2)는 f1을 실행한뒤 f2를 실행한다.
즉 f1에 의하여 x->3 이되고 f2에의하여 x->6이된다.
f2.compose(f1)은 f2을 실행한뒤 f1를 실행해 결과값이 5가된다.
identity 는 항등함수로서 함수를 적용하기 이전과 이후 동일한 결과가 필요할때 사용한다.
람다식으로 표현해보면 x -> x 이다.
Predicate에 정의된 메서드
test(), and(), or(), negate(), isEqual()
test() -> 추상메서드로서 우리가 원하는 타입의 파라미터를 통해 boolean을 return해준다.
List<String> list = Arrays.asList("apple", "banana", "cherry", "date");
Predicate<String> p1 = s -> s.length() > 4;
Predicate<String> p2 = s -> s.startsWith("c");
Predicate<String> p3 = Predicate.isEqual("apple");
// Use and to combine predicates
Predicate<String> pAnd = p1.and(p2); //and사용
System.out.println("Words with length greater than 4 and starting with 'c':");
list.stream().filter(pAnd).forEach(System.out::println);
// Use or to combine predicates
Predicate<String> pOr = p1.or(p2); //or사용
System.out.println("Words with length greater than 4 or starting with 'c':");
list.stream().filter(pOr).forEach(System.out::println);
// Use isEqual to compare for equality
System.out.println("Words that are equal to 'apple':");
list.stream().filter(p3).forEach(System.out::println);
//출력
Words with length greater than 4 and starting with 'c':
cherry
Words with length greater than 4 or starting with 'c':
banana
cherry
apple
Words that are equal to 'apple':
apple
- 위 코드는 and or isEqual 을 사용한 예제이다.
and()를 사용하여 글자수가 4이상이며 c로 시작하는 단어를 찾으면 결과값으로 cherry가 나오는것을 볼수있다.
- negate()는 조건식 전체를 부정하는 메서드이다.
List<String> list = Arrays.asList("apple", "banana", "cherry", "date");
Predicate<String> p = s -> s.length() > 4;
System.out.println("Words with length greater than 4:");
list.stream().filter(p).forEach(System.out::println);
// Use negate to reverse the result of the predicate
Predicate<String> pNegated = p.negate();
System.out.println("Words with length less than or equal to 4:");
list.stream().filter(pNegated).forEach(System.out::println);
Words with length greater than 4:
banana
cherry
date
Words with length less than or equal to 4:
apple
- 위 코드를 보면 .filter(pNegated) 로 인해 글자의 크기가 4이하인 단어 apple이 출력되는것을 볼수있다.
Reference
- Java의 정석
'CS' 카테고리의 다른 글
CS) Synchronous & Asynchronous (0) | 2023.02.12 |
---|---|
CS) 프로세스와 스레드 (0) | 2023.02.08 |
CS) Functional Programming (0) | 2023.02.08 |
CS) Mutable,Immutable (0) | 2023.02.08 |
CS) Tokenizer,Lexer,Parser (0) | 2023.02.08 |