Java

139. Predicate의 결합, CF와 함수형 인터페이스 - 패스트캠퍼스 백엔드 부트캠프 3기

gkss2tpt 2025. 1. 9. 16:58

1. Predicate의 결합

  • and(), or(), negate()[!not]로 두 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.add(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의 작성에는 isEquals()를 사용(static메서드)
Predicate<String> p = Predicate.isEqual(str1);	// isEquals()은 static메서드
Boolean result = p.test(str2);			//str1과 str2가 같은지 비교를 반환

boolean result = Predicate.isEqual(str1).test(str2);
public static void main(String[] args) {
        // 입력 String, 출력 Integer
        Function<String, Integer> f = (s) -> Integer.parseInt(s,16);
        // 입력 Integer, 출력 String
        Function<Integer, String> g = (i) -> Integer.toBinaryString(i);

        // String으로 들어오고 String으로 나간다.
        Function<String, String> h = f.andThen(g);  // f를 적용하고 g를 적용
        // Integer로 들어오고 Integer로 나간다.
        Function<Integer, Integer> h2 = f.compose(g);   // g를 적용하고 f를 적용

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

        Function<String, String> f2 = x -> x;   // 항등함수
        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));
        System.out.println(all.test(150));  // true

        String str1 = "abc";
        String str2 = "abc";

        // str1과 str2가 같은지 비교한 결과를 반환
        Predicate<String> p2 = Predicate.isEqual(str1);
        boolean result = p2.test(str2);
        System.out.println(result);
    }

 

2. 컬렉션 프레임웍과 함수형 인터페이스

  • 함수형 인터페이스를 사용하는 컬렉션 프레임웍의 메서드(와일드 카드 생략)
인터페이스 메서드 설명
Collection boolean removeIf(Predicate<E> filter) 조건에 맞는 요소를 삭제
List void replaceAll(UnaryOperator<E> operator) 모든 요소를 변환하여 대체
Iterable void forEach(Consumer<T> action) 모든 요소에 작업 action을 수행
Map V compute(K key, BiFunction<K,V,V> f) 지정된 키의 값에 작업 f를 수행
V computeIfAbsent(K key, Function<K,V> f) 키가 없으면, 작업 f 수행 후 추가
V computeIfPresent(K key, BiFunction<K,V,V> f) 지정된 키가 있을 때, 작업 f 수행
V merge(K key, V value, BiFunction<V,V,V> f) 모든 요소에 병합작업 f를 수행
void forEach(BiConsumer<K,V> action) 모든 요소에 작업 action을 수행
void replaceAll(BiFunction<K,V,V> f) 모든 요소에 치환작업 f를 수행

 

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+"},"));
public static void main(String[] args) {
        ArrayList<Integer> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            list.add(i);
        }

        // list의 모든 요소를 출력
        list.forEach(i-> System.out.print(i+","));
        System.out.println();

        // list에서 2 또는 3의 배수를 제거한다.
        list.removeIf(x-> x%2==0 || x%3==0);
        System.out.println(list);

        // list의 각요소에 10을 곱한다.
        list.replaceAll(i->i*10);
        System.out.println(list);

        Map<String, String> map = new HashMap<>();
        map.put("1","1");
        map.put("2","2");
        map.put("3","3");
        map.put("4","4");

        // map의 모든 요소를 {k,v}의 형식으로 출력한다.
        map.forEach((k,v) -> System.out.print("{"+k+","+v+"},"));
        System.out.println();
    }