@FunctionalInterface
public interface Predicate<T>{
boolean test(T t); // 반드시 구현해야하는 추상 메서드
default Predicate<T> and(Predicate<? super T> other); // 논리 AND
default Predicate<T> negate(); // 논리 OR
default Predicate<T> or(Predicate<? super T> other); // 논리 NOT
static <T> Predicate<T> isEqual(Object targetRef); // 정적 비교 생성기
}
- Java 8에 도입된 함수형 인터페이스(Function Interface) 중 하나
- boolean 값을 리턴하는 조건 판단용 함수를 정의할 때 사용됨
주요 메서드
조건 판별 📌
boolean test(T t);
- 조건을 만족하는지 판별
Predicate<String> isLong = s -> s.length() > 5;
System.out.println(isLong.test("hello")); // false
System.out.println(isLong.test("Charlie")); // true
AND 조건 결합 📌
default Predicate<T> and(Predicate<? super T> other)
- AND 조건 결합 (둘 다 true여야 true)
Predicate<String> isLong = s -> s.length() > 5;
Predicate<String> startsWithC = s -> s.startsWith("C");
Predicate<String> longAndStartsWithC = isLong.and(startsWithC);
System.out.println(longAndStartsWithC.test("Charlie")); // true
System.out.println(longAndStartsWithC.test("Chris")); // false (길이 조건 실패)
OR 조건 결합 📌
default Predicate<T> or(Predicate<? super T> other)
- OR 조건 결합 (둘 다 하나만 true여도 true)
Predicate<String> isShort = s -> s.length() < 4;
Predicate<String> startsWithA = s -> s.startsWith("A");
Predicate<String> shortOrStartsWithA = isShort.or(startsWithA);
System.out.println(shortOrStartsWithA.test("Al")); // true (시작 조건)
System.out.println(shortOrStartsWithA.test("Bob")); // true (짧은 이름)
System.out.println(shortOrStartsWithA.test("Charlie"));// false
NOT 조건 📌
default Predicate<T> negate()
- NOT 조건 (조건을 뒤집음)
Predicate<String> isEmpty = String::isEmpty;
Predicate<String> isNotEmpty = isEmpty.negate();
System.out.println(isNotEmpty.test("")); // false
System.out.println(isNotEmpty.test("data")); // true
같은지 비교 📌
static <T> Predicate<T> isEqual(Object targetRef)
- 같이 같은지를 비교하는 Predicate 반환
Predicate<String> isHello = Predicate.isEqual("hello");
System.out.println(isHello.test("hello")); // true
System.out.println(isHello.test("hi")); // false
'Java' 카테고리의 다른 글
Serializable 인터페이스 (0) | 2025.05.02 |
---|---|
Stream 인터페이스 (1) | 2025.05.02 |
참조타입 (reference type) (1) | 2025.05.01 |
기본타입 (primitive type) (0) | 2025.05.01 |
상속(inheritance) - JAVA (0) | 2025.05.01 |