diff --git a/pom.xml b/pom.xml index 5a3febe..174974b 100644 --- a/pom.xml +++ b/pom.xml @@ -80,6 +80,9 @@ maven-surefire-plugin 3.5.1 + + --enable-preview + diff --git a/src/main/java/com/pivovarit/gatherers/Gatherers.java b/src/main/java/com/pivovarit/gatherers/Gatherers.java deleted file mode 100644 index 45e2aa0..0000000 --- a/src/main/java/com/pivovarit/gatherers/Gatherers.java +++ /dev/null @@ -1,4 +0,0 @@ -package com.pivovarit.gatherers; - -class Gatherers { -} diff --git a/src/main/java/com/pivovarit/gatherers/MoreGatherers.java b/src/main/java/com/pivovarit/gatherers/MoreGatherers.java new file mode 100644 index 0000000..451935f --- /dev/null +++ b/src/main/java/com/pivovarit/gatherers/MoreGatherers.java @@ -0,0 +1,24 @@ +package com.pivovarit.gatherers; + +import java.util.Map; +import java.util.concurrent.atomic.AtomicLong; +import java.util.stream.Gatherer; + +import static java.util.stream.Gatherer.Integrator.ofGreedy; +import static java.util.stream.Gatherer.ofSequential; + +public final class MoreGatherers { + + private MoreGatherers() { + } + + public static Gatherer> zipWithIndex() { + return ofSequential( + AtomicLong::new, + ofGreedy((state, element, downstream) -> { + downstream.push(Map.entry(state.getAndIncrement(), element)); + return true; + }) + ); + } +} diff --git a/src/test/java/com/pivovarit/gatherers/ZipWithIndexTest.java b/src/test/java/com/pivovarit/gatherers/ZipWithIndexTest.java new file mode 100644 index 0000000..81f686f --- /dev/null +++ b/src/test/java/com/pivovarit/gatherers/ZipWithIndexTest.java @@ -0,0 +1,28 @@ +package com.pivovarit.gatherers; + +import org.junit.jupiter.api.Test; + +import java.util.stream.Stream; + +import static com.pivovarit.gatherers.MoreGatherers.zipWithIndex; +import static java.util.Map.entry; +import static org.assertj.core.api.Assertions.assertThat; + +class ZipWithIndexTest { + + @Test + void shouldZipEmptyStream() { + assertThat(Stream.empty().gather(zipWithIndex())).isEmpty(); + } + + @Test + void shouldZipWithIndex() { + assertThat(Stream.of("a", "b", "c") + .gather(zipWithIndex())) + .containsExactly( + entry(0L, "a"), + entry(1L, "b"), + entry(2L, "c") + ); + } +}