Skip to content

Commit a453e4d

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

File tree

2 files changed

+49
-1
lines changed

2 files changed

+49
-1
lines changed
Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,24 @@
11
package com.pivovarit.gatherers;
22

3-
class Gatherers {
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 Gatherers {
11+
12+
private Gatherers() {
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+
}
424
}
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.Gatherers.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)