Skip to content

Commit

Permalink
Add MoreGatherers.zipWithIndex() (#27)
Browse files Browse the repository at this point in the history
  • Loading branch information
pivovarit authored Oct 11, 2024
1 parent f6bb76b commit 03c8c10
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 0 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ Provided `Gatherers`:
- `MoreGatherers.zip(Stream<T2>, BiFunction<T1,T2>)`
- `MoreGatherers.zipWithIterable(Iterable<T2>)`
- `MoreGatherers.zipWithIterable(Iterable<T2>, BiFunction<T1,T2>)`
- `MoreGatherers.zipWithIndex()`
- `MoreGatherers.zipWithIndex(BiFunction<Long,T>)`
- `MoreGatherers.distinctBy(Function<T, R>)`
- `MoreGatherers.distinctByKeepLast(Function<T, R>)`
- `MoreGatherers.distinctUntilChanged()`
Expand Down
12 changes: 12 additions & 0 deletions src/main/java/com/pivovarit/gatherers/MoreGatherers.java
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,18 @@ class State {
});
}

public static <T, R> Gatherer<T, ?, R> zipWithIndex(BiFunction<Long, ? super T, ? extends R> mapper) {
Objects.requireNonNull(mapper, "mapper can't be null");

return ofSequential(
AtomicLong::new,
ofGreedy((state, element, downstream) -> {
downstream.push(mapper.apply(state.getAndIncrement(), element));
return true;
})
);
}

public static <T> Gatherer<T, ?, Map.Entry<Long, T>> zipWithIndex() {
return ofSequential(
AtomicLong::new,
Expand Down
29 changes: 29 additions & 0 deletions src/test/java/com/pivovarit/gatherers/ZipWithIndexMapperTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package com.pivovarit.gatherers;

import org.junit.jupiter.api.Test;

import java.util.stream.Stream;

import static com.pivovarit.gatherers.MoreGatherers.zipWithIndex;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;

class ZipWithIndexMapperTest {

@Test
void shouldRejectNullMapper() {
assertThatThrownBy(() -> zipWithIndex(null)).isInstanceOf(NullPointerException.class);
}

@Test
void shouldZipEmptyStream() {
assertThat(Stream.empty().gather(zipWithIndex((idx, i) -> "" + idx + i))).isEmpty();
}

@Test
void shouldZipWithIndex() {
assertThat(Stream.of("a", "b", "c")
.gather(zipWithIndex((idx, i) -> idx + i)))
.containsExactly("0a", "1b", "2c");
}
}

0 comments on commit 03c8c10

Please sign in to comment.