Skip to content

Commit 654d397

Browse files
feat: added initalizer, integrator, finisher examples
1 parent 1f5a409 commit 654d397

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

src/main/java/de/claudioaltamura/java23/streamgatherer/StreamGathererExample.java

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package de.claudioaltamura.java23.streamgatherer;
22

33
import java.util.List;
4+
import java.util.ArrayList;
45
import java.util.concurrent.atomic.AtomicInteger;
56
import java.util.function.Function;
67
import java.util.stream.Gatherer;
@@ -54,4 +55,34 @@ public List<String> firstThreeWords(List<String> words) {
5455
.toList();
5556
}
5657

58+
public <T> Gatherer<T, List<T>, List<T>> windowing(int windowSize) {
59+
return Gatherer.ofSequential(
60+
// Initializer
61+
ArrayList::new,
62+
63+
// Gatherer
64+
(state, element, downstream) -> {
65+
state.add(element);
66+
if (state.size() == windowSize) {
67+
boolean result = downstream.push(List.copyOf(state));
68+
state.clear();
69+
return result;
70+
} else {
71+
return true;
72+
}
73+
},
74+
75+
// Finisher
76+
(state, downstream) -> {
77+
if (!state.isEmpty()) {
78+
downstream.push(List.copyOf(state));
79+
}
80+
});
81+
}
82+
83+
public List<List<String>> groupWords(List<String> words, int groupSize) {
84+
return words.stream()
85+
.gather(windowing(groupSize))
86+
.toList();
87+
}
5788
}

src/test/java/de/claudioaltamura/java23/streamgatherer/StreamGathererExampleTest.java

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,4 +34,14 @@ void firstThreeWords() {
3434
assertThat(result).contains("Hello", "beautiful", "world");
3535
}
3636

37+
@Test
38+
void groupWords() {
39+
var groupSize = 2;
40+
final List<List<String>> result = streamGathererExample.groupWords(List.of("Hello", "beautiful", "world", "You", "are", "nice"), groupSize);
41+
42+
assertThat(result).hasSize(3);
43+
assertThat(result.getFirst()).contains("Hello", "beautiful");
44+
assertThat(result.get(1)).contains("world", "You");
45+
assertThat(result.getLast()).contains("are", "nice");
46+
}
3747
}

0 commit comments

Comments
 (0)