Skip to content

Commit dd8106b

Browse files
feat: simple stream gatherer example
1 parent 95a06e3 commit dd8106b

File tree

3 files changed

+46
-2
lines changed

3 files changed

+46
-2
lines changed

README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,5 +4,5 @@ Java 23 feature examples
44
* Markdown documentation
55
* maven-javadoc-plugin version 3.10.1 not working
66
* Module Import Declaration
7-
* Primitive Types in Patterns, instanceof, and switch (Preview) – JEP 455
8-
* Stream Gatherer
7+
* Primitive Types in Patterns, instanceof, and switch (Preview)
8+
* Stream Gatherer (Preview)
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package de.claudioaltamura.java23.streamgatherer;
2+
3+
import java.util.List;
4+
import java.util.function.Function;
5+
import java.util.stream.Gatherer;
6+
7+
public class StreamGathererExample {
8+
9+
public <T, R> Gatherer<T, Void, R> mapping(Function<T, R> mapper) {
10+
return Gatherer.of(
11+
Gatherer.Integrator.ofGreedy(
12+
(state, element, downstream) -> {
13+
R mappedElement = mapper.apply(element);
14+
return downstream.push(mappedElement);
15+
}));
16+
}
17+
18+
public List<Integer> toLengths(List<String> words) {
19+
return words.stream()
20+
.gather(mapping(String::length))
21+
.toList();
22+
}
23+
24+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package de.claudioaltamura.java23.streamgatherer;
2+
3+
import org.junit.jupiter.api.Test;
4+
5+
import java.util.List;
6+
7+
import static org.assertj.core.api.Assertions.assertThat;
8+
9+
10+
class StreamGathererExampleTest {
11+
12+
@Test
13+
void toLengths() {
14+
final var streamGathererExample = new StreamGathererExample();
15+
16+
var result = streamGathererExample.toLengths(List.of("this", "is", "a", "list"));
17+
18+
assertThat(result).containsAll(List.of(4,2,1,4));
19+
}
20+
}

0 commit comments

Comments
 (0)