✅ 1. Predicate<T>
Package: java.util.function
- A functional interface that takes one argument of type
T
and returns aboolean
.
@FunctionalInterface
public interface Predicate<T> {
boolean test(T t);
}
🧠 Example:
Predicate<String> isLongWord = str -> str.length() > 5;
System.out.println(isLongWord.test("hello")); // false
System.out.println(isLongWord.test("predicate")); // true
🔧 Use Cases:
- Filtering elements in streams:
List<String> list = List.of("cat", "elephant", "bat");
list.stream().filter(isLongWord).forEach(System.out::println);
Combine with .and()
, .or()
, .negate()
:
Predicate<String> startsWithE = s -> s.startsWith("e");
Predicate<String> complex = isLongWord.and(startsWithE);
✅ 2. IntPredicate
Used for primitive int
, avoids boxing overhead.
@FunctionalInterface
public interface IntPredicate {
boolean test(int value);
}
✅ 3. LongPredicate
Same idea for long
.
@FunctionalInterface
public interface LongPredicate {
boolean test(long value);
}
✅ 4. DoublePredicate
For double
primitives.
@FunctionalInterface
public interface DoublePredicate {
boolean test(double value);
}
🧠 Example:
DoublePredicate isBetween0And1 = d -> d > 0 && d < 1;
System.out.println(isBetween0And1.test(0.5)); // true
🔄 Summary Table:
Interface | Input Type | Return Type | Use Case Example |
---|---|---|---|
Predicate<T> | T | boolean | str -> str.length() > 5 |
IntPredicate | int | boolean | x -> x % 2 == 0 |
LongPredicate | long | boolean | l -> l > 0 |
DoublePredicate | double | boolean | d -> d > 0 && d < 1 |