In this post, we will learn “How to use Predicate ‘not’ method introduced in Java 11?”.
Here, we are going to learn the following things:
- What is the Predicate not() method?
- How to use it?
Predicate not() in Java 11...!!! Click To Tweet
Let’s Begin,
1. What is the Predicate not() method?
This method returns a predicate that is the logical negation of the given predicate.
2. How to use it?
Let’s take an example where we have the lambda expression to retrieve ‘Even’ numbers and to get ‘Odd’ numbers, we are going to use ‘not()’ method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | import java.util.Arrays; import java.util.List; import java.util.function.Predicate; import java.util.stream.Collectors; public class Predicate_NOT_with_ArrayList_Java8 { public static void main(String[] args) { List <Integer> list = Arrays.asList(1, 2, 3, 4, 5); Predicate <Integer> isEven = i -> i % 2 == 0; Predicate <Integer> isOdd = Predicate.not(isEven); List <Integer> evenNumbers = list.stream().filter(isEven).collect(Collectors.toList()); List <Integer> oddNumbers = list.stream().filter(isOdd).collect(Collectors.toList()); System.out.println("Even Numbers:\n" + evenNumbers); System.out.println("\nOdd Numbers:\n" + oddNumbers); } } |
Output:
1 2 3 4 5 | Even Numbers: [2, 4] Odd Numbers: [1, 3, 5] |
Predicate not() in Java 11...!!! Click To Tweet
Do you like this Post? – then check my other helpful posts: