Predicate Interface is a part of the java.util.function package which is introduced in Java 8. Predicate Negate returns the logical negation of the given predicate. In this post, we are going to see a few implementations of how to use it.
Predicate Negate in Java 8 with Examples...!!! Click To Tweet
Example 1. with ArrayList
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | import java.util.Arrays; import java.util.List; import java.util.function.Predicate; import java.util.stream.Collectors; public class PredicateInterface_Negate_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 = isEven.negate(); 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); } } |
Example 2. using IntStream
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | package org.personal.samples; import java.util.function.IntPredicate; import java.util.stream.IntStream; public class PredicateInterface_Negate_with_IntStream_Java8 { public static void main(String[] args) { IntPredicate isEven = i -> i % 2 == 0; IntPredicate isOdd = isEven.negate(); System.out.println("Even Numbers:\n"); IntStream.of(1, 2, 3, 4, 5).filter(isEven).forEach(System.out::println); System.out.println("\nOdd Numbers:\n"); IntStream.of(1, 2, 3, 4, 5).filter(isOdd).forEach(System.out::println); } } |
Predicate Negate in Java 8 with Examples...!!! Click To Tweet
Do you like this Post? – then check my other helpful posts:
- Passing Function as a Parameter in another Method in Java 8
- Collection sorting using Lambda in Java 8
- Supplier Interface in Java 8 with Examples