Skip to content

Commit

Permalink
Introduce dedicated ZipWithIndexMappingGatherer
Browse files Browse the repository at this point in the history
  • Loading branch information
pivovarit committed Oct 14, 2024
1 parent 48e7898 commit 3e2704b
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 9 deletions.
10 changes: 1 addition & 9 deletions src/main/java/com/pivovarit/gatherers/MoreGatherers.java
Original file line number Diff line number Diff line change
Expand Up @@ -124,15 +124,7 @@ 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;
})
);
return new ZipWithIndexMappingGatherer<>(mapper);
}

public static <T> Gatherer<T, ?, Map.Entry<Long, T>> zipWithIndex() {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package com.pivovarit.gatherers;

import java.util.Objects;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.BiFunction;
import java.util.function.Supplier;
import java.util.stream.Gatherer;

record ZipWithIndexMappingGatherer<T, R>(BiFunction<Long, ? super T, ? extends R> mapper)
implements Gatherer<T, AtomicLong, R> {

ZipWithIndexMappingGatherer {
Objects.requireNonNull(mapper, "mapper can't be null");
}

@Override
public Supplier<AtomicLong> initializer() {
return AtomicLong::new;
}

@Override
public Integrator<AtomicLong, T, R> integrator() {
return Integrator.ofGreedy((state, element, downstream) -> {
downstream.push(mapper.apply(state.getAndIncrement(), element));
return true;
});
}
}

0 comments on commit 3e2704b

Please sign in to comment.