-
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
4 changed files
with
55 additions
and
4 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
28
src/test/java/com/pivovarit/gatherers/ZipWithIndexTest.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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") | ||
); | ||
} | ||
} |