-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPredicateNot.java
More file actions
80 lines (60 loc) · 2.74 KB
/
Copy pathPredicateNot.java
File metadata and controls
80 lines (60 loc) · 2.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package java11.predicate;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
/**
* Java 11 Predicate.not() Method
* Demonstrates negating predicates with Predicate.not()
*/
public class PredicateNot {
public static void main(String[] args) {
List<String> names = Arrays.asList("Alice", "", "Bob", " ", "Charlie", "");
// 1. Predicate.not() - Negate a predicate
System.out.println("=== Predicate.not() Examples ===");
// Filter non-blank strings
List<String> nonBlank = names.stream()
.filter(Predicate.not(String::isBlank))
.collect(Collectors.toList());
System.out.println("Original: " + names);
System.out.println("Non-blank: " + nonBlank);
// 2. Comparison with old approach
System.out.println("\n=== Comparison ===");
// Old way (before Java 11)
List<String> oldWay = names.stream()
.filter(s -> !s.isBlank())
.collect(Collectors.toList());
// New way (Java 11)
List<String> newWay = names.stream()
.filter(Predicate.not(String::isBlank))
.collect(Collectors.toList());
System.out.println("Old way: " + oldWay);
System.out.println("New way: " + newWay);
// 3. With method references
System.out.println("\n=== With Method References ===");
List<String> nonEmpty = names.stream()
.filter(Predicate.not(String::isEmpty))
.collect(Collectors.toList());
System.out.println("Non-empty: " + nonEmpty);
// 4. Complex predicates
System.out.println("\n=== Complex Predicates ===");
Predicate<String> isShort = s -> s.length() <= 3;
List<String> notShort = names.stream()
.filter(Predicate.not(isShort))
.collect(Collectors.toList());
System.out.println("Not short (length > 3): " + notShort);
// 5. Practical example
System.out.println("\n=== Practical Example ===");
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
// Filter even numbers
List<Integer> evens = numbers.stream()
.filter(Predicate.not(n -> n % 2 != 0))
.collect(Collectors.toList());
System.out.println("Even numbers: " + evens);
// Filter numbers not divisible by 3
List<Integer> notDivisibleBy3 = numbers.stream()
.filter(Predicate.not(n -> n % 3 == 0))
.collect(Collectors.toList());
System.out.println("Not divisible by 3: " + notDivisibleBy3);
}
}