Skip to content

Commit 1f5a409

Browse files
feat: added initalizer, integrator examples
1 parent 008b95a commit 1f5a409

File tree

2 files changed

+37
-5
lines changed

2 files changed

+37
-5
lines changed

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

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

33
import java.util.List;
4+
import java.util.concurrent.atomic.AtomicInteger;
45
import java.util.function.Function;
56
import java.util.stream.Gatherer;
67
import java.util.stream.Gatherers;
78

9+
/**
10+
* Stream gatherer example.
11+
* see <a href="https://www.happycoders.eu/de/java/stream-gatherers/">stream-gatherers</a>
12+
*/
813
public class StreamGathererExample {
914

1015
public <T, R> Gatherer<T, Void, R> mapping(Function<T, R> mapper) {
@@ -28,4 +33,25 @@ public List<List<String>> groupsOfThree(List<String> words) {
2833
.toList();
2934
}
3035

36+
public <T> Gatherer<T, AtomicInteger, T> limiting(int maxSize) {
37+
return Gatherer.ofSequential(
38+
// Initializer
39+
AtomicInteger::new,
40+
41+
// Integrator
42+
(state, element, downstream) -> {
43+
if (state.getAndIncrement() < maxSize) {
44+
return downstream.push(element);
45+
} else {
46+
return false;
47+
}
48+
});
49+
}
50+
51+
public List<String> firstThreeWords(List<String> words) {
52+
return words.stream()
53+
.gather(limiting(3))
54+
.toList();
55+
}
56+
3157
}

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

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,23 +9,29 @@
99

1010
class StreamGathererExampleTest {
1111

12+
private final StreamGathererExample streamGathererExample = new StreamGathererExample();
13+
1214
@Test
1315
void toLengths() {
14-
final var streamGathererExample = new StreamGathererExample();
15-
1616
var result = streamGathererExample.toLengths(List.of("this", "is", "a", "list"));
1717

1818
assertThat(result).containsAll(List.of(4,2,1,4));
1919
}
2020

2121
@Test
22-
void testeGroupOfThree() {
23-
final var streamGathererExample = new StreamGathererExample();
24-
22+
void groupOfThree() {
2523
final List<List<String>> result = streamGathererExample.groupsOfThree(List.of("Hello", "beautiful", "world", "You", "are", "nice"));
2624

2725
assertThat(result).hasSize(2);
2826
assertThat(result.getFirst()).contains("Hello", "beautiful", "world");
2927
assertThat(result.getLast()).contains("You", "are", "nice");
3028
}
29+
30+
@Test
31+
void firstThreeWords() {
32+
final List<String> result = streamGathererExample.firstThreeWords(List.of("Hello", "beautiful", "world", "You", "are", "nice"));
33+
34+
assertThat(result).contains("Hello", "beautiful", "world");
35+
}
36+
3137
}

0 commit comments

Comments
 (0)