Predicate in Java

Predicate in Java

In Java, Predicate is a functional interface that is part of the java.util.function package introduced in Java 8. It represents a single argument function that returns a boolean value. The Predicate functional interface is often used for filtering and testing elements in collections, streams, and various other scenarios where you need to evaluate a condition.

The Predicate interface defines a single abstract method:

boolean test(T t); 

Here's a breakdown of how to use Predicate in Java:

  1. Import the Predicate Interface: Import the Predicate interface from the java.util.function package:

    import java.util.function.Predicate; 
  2. Creating a Predicate: You can create a Predicate by defining a lambda expression or method reference that implements the test method. The lambda expression or method reference should evaluate a condition and return a boolean value.

    Predicate<Integer> isEven = n -> n % 2 == 0; 

    In this example, isEven is a Predicate that tests whether an integer is even.

  3. Using a Predicate: Once you have a Predicate, you can use it to evaluate conditions on elements. Common scenarios include filtering elements in collections or streams:

    List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); List<Integer> evenNumbers = numbers.stream() .filter(isEven) .collect(Collectors.toList()); // evenNumbers will contain [2, 4, 6, 8, 10] 

    In this example, the isEven Predicate is used with the filter operation to select even numbers from a list.

  4. Combining Predicates: You can combine Predicate instances using logical operations like and, or, and negate to create more complex conditions:

    Predicate<Integer> isGreaterThan5 = n -> n > 5; Predicate<Integer> isEvenAndGreaterThan5 = isEven.and(isGreaterThan5); // Use isEvenAndGreaterThan5 in a filter operation 

    The isEvenAndGreaterThan5 Predicate will match numbers that are both even and greater than 5.

  5. Negating a Predicate: You can negate a Predicate using the negate method to create a new Predicate with the opposite condition:

    Predicate<Integer> isNotEven = isEven.negate(); // Use isNotEven in a filter operation to select non-even numbers 

    The isNotEven Predicate will match numbers that are not even.

The Predicate interface is a powerful tool for expressing conditions and filtering elements in a concise and functional way. It's commonly used in conjunction with Java collections, streams, and other functional programming constructs.


More Tags

ora-01017 npoi unicode-escapes persist java-12 jwk uistoryboardsegue google-analytics edmx-designer android-2.2-froyo

More Java Questions

More General chemistry Calculators

More Electrochemistry Calculators

More Genetics Calculators

More Chemical thermodynamics Calculators