Java.Java8.What are the functional interfaces Predicate, DoublePredicate, IntPredicate, and LongPredicate?

✅ 1. Predicate<T>

Package: java.util.function

  • A functional interface that takes one argument of type T and returns a boolean.
@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:

InterfaceInput TypeReturn TypeUse Case Example
Predicate<T>Tbooleanstr -> str.length() > 5
IntPredicateintbooleanx -> x % 2 == 0
LongPredicatelongbooleanl -> l > 0
DoublePredicatedoublebooleand -> d > 0 && d < 1
This entry was posted in Без рубрики. Bookmark the permalink.