To use Predicate.not() in streams, you take advantage of its ability to negate an existing predicate. This can be helpful in filter operations where you want to filter out elements that match a given condition instead of including them.
Here’s how you can use Predicate.not in streams:
Basic Explanation
- What it does: The
Predicate.not()method is a static method (added in Java 11) that creates a predicate that negates the specified predicate. Instead of writing complex logic for negation, you can directly usePredicate.not()for cleaner and more readable code. -
Use Case in Streams: When working with Java Streams, you often use
.filter()to include elements that satisfy a condition. If you want to exclude elements that satisfy a condition, you can usePredicate.not().
Example: Using Predicate.not() in a Stream
package org.kodejava.util.function;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public class PredicateNotExample {
public static void main(String[] args) {
// Define a list of integers
List<Integer> numbers = List.of(5, 15, 8, 25, 3, 12);
// Define a predicate to filter numbers greater than 10
Predicate<Integer> isGreaterThan10 = number -> number > 10;
// Use Predicate.not() to filter numbers NOT greater than 10
List<Integer> filteredNumbers = numbers.stream()
.filter(Predicate.not(isGreaterThan10))
.collect(Collectors.toList());
// Print the filtered list
System.out.println(filteredNumbers); // Output: [5, 8, 3]
}
}
Breakdown of the Code:
-
Define Predicate
A predicate is defined (isGreaterThan10) to test if a number is greater than 10. -
Stream Filtering
- Using
.stream()to process the list of numbers. .filter(Predicate.not(isGreaterThan10))negates the predicate, effectively including numbers less than or equal to 10.
- Using
-
Collect Results
The result is collected using.collect(Collectors.toList()).
Why Use Predicate.not()?
-
Improved Readability: Instead of writing a negation explicitly like
x -> !isGreaterThan10.test(x), you can usePredicate.not(isGreaterThan10)for better readability. -
Reusability:
Predicate.not()can work for any predicate, making it easier to reuse your existing predicates in multiple ways. -
Less Prone to Errors: Writing custom negation logic in lambdas may lead to errors or make the code harder to understand.
Predicate.not()makes intent clear and reduces the chance of mistakes.
Notes:
- The
Predicate.not()method was introduced in Java 11. Ensure you are using Java 11 or later to use it. - You can apply this with any kind of predicate—numerical, string-based, or custom objects.
