Skip to content

Commit

Permalink
Add Gatherers.zipWithIndex()
Browse files Browse the repository at this point in the history
  • Loading branch information
pivovarit committed Oct 7, 2024
1 parent 22c2d85 commit cd13954
Show file tree
Hide file tree
Showing 4 changed files with 55 additions and 4 deletions.
3 changes: 3 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,9 @@
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<argLine>--enable-preview</argLine>
</configuration>
</plugin>

<plugin>
Expand Down
4 changes: 0 additions & 4 deletions src/main/java/com/pivovarit/gatherers/Gatherers.java

This file was deleted.

24 changes: 24 additions & 0 deletions src/main/java/com/pivovarit/gatherers/MoreGatherers.java
Original file line number Diff line number Diff line change
@@ -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 <T> Gatherer<T, ?, Map.Entry<Long, T>> zipWithIndex() {
return ofSequential(
AtomicLong::new,
ofGreedy((state, element, downstream) -> {
downstream.push(Map.entry(state.getAndIncrement(), element));
return true;
})
);
}
}
28 changes: 28 additions & 0 deletions src/test/java/com/pivovarit/gatherers/ZipWithIndexTest.java
Original file line number Diff line number Diff line change
@@ -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")
);
}
}

0 comments on commit cd13954

Please sign in to comment.