study

function 패키지 사용법, BiPredicate<T,U>

BiPredicate<T,U>

import java.util.Map;
import java.util.function.BiPredicate;

public class BiPredicateTest {

    public static void main(String... strings) {

        // BiPredicate<T, U> : 두 입력 → boolean
        BiPredicate<String, String> equalsIgnoreCase = (s1, s2) -> s1.equalsIgnoreCase(s2);
        System.out.println(equalsIgnoreCase.test("hello", "HELLO")); // true

        BiPredicate<Integer, Integer> greaterThan = (a, b) -> a < b;
        System.out.println(greaterThan.test(5, 3)); // false

        // 주요 메소드 and, or, negate
        BiPredicate<String, Integer> checkLength = (s, len) -> s.length() == len;
        BiPredicate<String, Integer> notEmpty = (s, len) -> !s.isEmpty();
        BiPredicate<String, Integer> andTest = checkLength.and(notEmpty);
        BiPredicate<String, Integer> orTest = checkLength.or(notEmpty);
        BiPredicate<String, Integer> notEqualLength = checkLength.negate();
        System.out.println(andTest.test("hello", 5)); // true
        System.out.println(orTest.test("hi", 5)); // true (2 < 5)
        System.out.println(notEqualLength.test("hello", 5)); // false
        System.out.println(notEqualLength.test("world", 3)); // true

        // Map 필터링
        Map<String, Integer> map = Map.of("apple", 5, "banana", 2, "cherry", 7);
        BiPredicate<String, Integer> filter = (key, value) -> key.startsWith("a") && value > 3;

        map.forEach((k, v) -> {
            if (filter.test(k, v)) {
                System.out.println("조건 만족: " + k + "=" + v); // 조건 만족: apple=5
            }
        });
    }
}