Skip to content

Commit d6dce6f

Browse files
committed
Add Gatherers.zipWithIndex()
1 parent f680153 commit d6dce6f

File tree

4 files changed

+55
-4
lines changed

4 files changed

+55
-4
lines changed

pom.xml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,9 @@
8080
<plugin>
8181
<artifactId>maven-surefire-plugin</artifactId>
8282
<version>3.5.1</version>
83+
<configuration>
84+
<argLine>--enable-preview</argLine>
85+
</configuration>
8386
</plugin>
8487

8588
<plugin>

src/main/java/com/pivovarit/gatherers/Gatherers.java

Lines changed: 0 additions & 4 deletions
This file was deleted.
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package com.pivovarit.gatherers;
2+
3+
import java.util.Map;
4+
import java.util.concurrent.atomic.AtomicLong;
5+
import java.util.stream.Gatherer;
6+
7+
import static java.util.stream.Gatherer.Integrator.ofGreedy;
8+
import static java.util.stream.Gatherer.ofSequential;
9+
10+
public final class MoreGatherers {
11+
12+
private MoreGatherers() {
13+
}
14+
15+
public static <T> Gatherer<T, ?, Map.Entry<Long, T>> zipWithIndex() {
16+
return ofSequential(
17+
AtomicLong::new,
18+
ofGreedy((state, element, downstream) -> {
19+
downstream.push(Map.entry(state.getAndIncrement(), element));
20+
return true;
21+
})
22+
);
23+
}
24+
}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package com.pivovarit.gatherers;
2+
3+
import org.junit.jupiter.api.Test;
4+
5+
import java.util.stream.Stream;
6+
7+
import static com.pivovarit.gatherers.MoreGatherers.zipWithIndex;
8+
import static java.util.Map.entry;
9+
import static org.assertj.core.api.Assertions.assertThat;
10+
11+
class ZipWithIndexTest {
12+
13+
@Test
14+
void shouldZipEmptyStream() {
15+
assertThat(Stream.empty().gather(zipWithIndex())).isEmpty();
16+
}
17+
18+
@Test
19+
void shouldZipWithIndex() {
20+
assertThat(Stream.of("a", "b", "c")
21+
.gather(zipWithIndex()))
22+
.containsExactly(
23+
entry(0L, "a"),
24+
entry(1L, "b"),
25+
entry(2L, "c")
26+
);
27+
}
28+
}

0 commit comments

Comments
 (0)