-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIntermediateOperations.java
More file actions
168 lines (151 loc) · 6.95 KB
/
Copy pathIntermediateOperations.java
File metadata and controls
168 lines (151 loc) · 6.95 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
package Phase5_CollectionsLambdasStreams.LambdaAndStreams;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Intermediate Operations - The Lazy Transformations
* --------------------------------------------------
* Intermediate operations RETURN A NEW STREAM and do not run until a
* terminal operation pulls them. Most are STATELESS - they process each
* element independently. A few are STATEFUL and must see multiple elements
* to decide.
* <p>
*
* Stateless
* ---------
* filter(Predicate) keep only elements matching the predicate
* map(Function) transform T -> R
* mapToInt / mapToLong / mapToDouble
* flatMap(Function) T -> Stream<R>, flatten one level
* peek(Consumer) side effect on each element (debug)
* <p>
*
* Stateful
* --------
* sorted() natural order (T must be Comparable)
* sorted(Comparator) custom order
* distinct() de-dup using equals
* limit(long n) keep first n
* skip(long n) drop first n
* takeWhile(Predicate) take while the predicate holds (Java 9+)
* dropWhile(Predicate) drop while the predicate holds (Java 9+)
* <p>
*
* mapMulti (Java 16+) - 1 element to MANY without an intermediate Stream
* ---------------------------------------------------------------------
* stream.mapMulti((t, downstream) -> {
* if (cond) downstream.accept(t);
* downstream.accept(other);
* });
* <p>
*
* It is faster than flatMap when each element produces only a small,
* computable set of results.
* <p>
*
* One element per row - the table
* -------------------------------
* OP TYPE STATEFUL? SHORT-CIRCUIT?
* filter T -> T no no
* map T -> R no no
* flatMap T -> R* no no
* peek T -> T no no
* sorted T -> T YES no
* distinct T -> T YES no
* limit T -> T YES YES
* skip T -> T YES no
* takeWhile T -> T YES YES (J9+)
* dropWhile T -> T YES no (J9+)
* mapMulti T -> R* no no (J16+)
*/
public class IntermediateOperations {
public static void main(String[] args) {
section("1) filter - keep elements that match");
List<Integer> nums = List.of(3, 1, 4, 1, 5, 9, 2, 6);
List<Integer> evens = nums.stream()
.filter(n -> n % 2 == 0)
.collect(Collectors.toList());
System.out.println("evens = " + evens);
section("2) map - one-to-one transformation");
List<Integer> lengths = Stream.of("alpha", "beta", "gamma")
.map(String::length)
.collect(Collectors.toList());
System.out.println("lengths = " + lengths);
section("3) flatMap - one-to-many, then flatten");
List<List<Integer>> nested = List.of(
List.of(1, 2, 3),
List.of(4, 5),
List.of(6, 7, 8, 9)
);
List<Integer> flat = nested.stream()
.flatMap(List::stream)
.collect(Collectors.toList());
System.out.println("flat = " + flat);
// flatMap to split sentences into words
List<String> words = Stream.of("the quick brown", "fox jumps over", "the lazy dog")
.flatMap(line -> Arrays.stream(line.split(" ")))
.collect(Collectors.toList());
System.out.println("words = " + words);
section("4) sorted - natural and custom");
List<Integer> sortedAsc = nums.stream().sorted().collect(Collectors.toList());
List<Integer> sortedDesc = nums.stream()
.sorted(Comparator.reverseOrder())
.collect(Collectors.toList());
System.out.println("asc = " + sortedAsc);
System.out.println("desc = " + sortedDesc);
// Custom comparator on objects
record P(String name, int age) {}
List<P> people = List.of(
new P("Charlie", 30),
new P("Alice", 28),
new P("Bob", 34)
);
people.stream()
.sorted(Comparator.comparingInt(P::age))
.forEach(System.out::println);
section("5) distinct - remove duplicates");
List<Integer> u = Stream.of(3, 1, 4, 1, 5, 9, 2, 6, 5, 3)
.distinct()
.collect(Collectors.toList());
System.out.println("distinct = " + u);
section("6) skip + limit - pagination idiom");
List<Integer> page2 = Stream.iterate(1, n -> n + 1)
.skip(10) // skip page 1
.limit(5) // 5 items per page
.collect(Collectors.toList());
System.out.println("page 2 = " + page2);
section("7) takeWhile / dropWhile (Java 9+)");
// Both stop / start based on a CONDITION rather than an INDEX.
List<Integer> taken = Stream.of(1, 2, 3, 4, 5, 1, 2)
.takeWhile(n -> n < 4)
.collect(Collectors.toList()); // [1, 2, 3]
List<Integer> dropped = Stream.of(1, 2, 3, 4, 5, 1, 2)
.dropWhile(n -> n < 4)
.collect(Collectors.toList()); // [4, 5, 1, 2]
System.out.println("takeWhile = " + taken);
System.out.println("dropWhile = " + dropped);
// takeWhile stops at the first element that FAILS the predicate -
// unlike filter, which keeps scanning.
section("8) peek - SIDE-EFFECT debugging only");
long count = nums.stream()
.peek(n -> System.out.println(" before filter : " + n))
.filter(n -> n > 2)
.peek(n -> System.out.println(" after filter : " + n))
.count();
System.out.println("count = " + count);
section("9) mapMulti (Java 16+) - faster than flatMap for tiny expansions");
List<Integer> expanded = Stream.of(1, 2, 3)
.<Integer>mapMulti((n, sink) -> {
sink.accept(n);
sink.accept(n * 10);
})
.collect(Collectors.toList());
System.out.println("mapMulti = " + expanded); // [1, 10, 2, 20, 3, 30]
// OUTPUT (representative)
}
private static void section(String title) {
System.out.println("\n====== " + title + " ======");
}
}