Sobes.tech
Middle

For what are functional interfaces Predicate<T>, DoublePredicate, IntPredicate, and LongPredicate used?

sobes.tech AI

Answer from AI

Functional interfaces Predicate<T>, DoublePredicate, IntPredicate, and LongPredicate are used to represent a boolean test that takes one argument and returns a boolean value (true or false).

  • Predicate<T>: A generic predicate applicable to objects of any type T.
    // Example of using Predicate<String>
    Predicate<String> isNotEmpty = s -> !s.isEmpty();
    boolean result = isNotEmpty.test("Hello"); // result will be true
    
  • DoublePredicate: A specialized predicate for the primitive type double.
    // Example of using DoublePredicate
    DoublePredicate isPositive = d -> d > 0.0;
    boolean result = isPositive.test(10.5); // result will be true
    
  • IntPredicate: A specialized predicate for the primitive type int.
    // Example of using IntPredicate
    IntPredicate isEven = i -> i % 2 == 0;
    boolean result = isEven.test(4); // result will be true
    
  • LongPredicate: A specialized predicate for the primitive type long.
    // Example of using LongPredicate
    LongPredicate isLarge = l -> l > 1000L;
    boolean result = isLarge.test(2000L); // result will be true
    

Using these specialized predicates for primitive types helps avoid autoboxing and the associated overhead, improving performance when working with large volumes of primitive data. They are often used in streams (Stream, DoubleStream, IntStream, LongStream) for filtering operations (filter).