Skip to content

Commit

Permalink
Introduce dedicated ZipIteratorGatherer (#35)
Browse files Browse the repository at this point in the history
  • Loading branch information
pivovarit authored Oct 14, 2024
1 parent a9f140f commit 6fb6341
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 17 deletions.
18 changes: 1 addition & 17 deletions src/main/java/com/pivovarit/gatherers/MoreGatherers.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,11 @@
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.stream.Gatherer;
import java.util.stream.Stream;

import static java.util.stream.Gatherer.Integrator.ofGreedy;
import static java.util.stream.Gatherer.ofSequential;

public final class MoreGatherers {

private MoreGatherers() {
Expand Down Expand Up @@ -108,19 +104,7 @@ class State {
}

public static <T1, T2, R> Gatherer<T1, ?, R> zip(Iterator<T2> iterator, BiFunction<? super T1, ? super T2, ? extends R> mapper) {
Objects.requireNonNull(mapper, "mapper can't be null");
Objects.requireNonNull(iterator, "iterator can't be null");

return Gatherer.ofSequential(
() -> iterator,
(state, element, downstream) -> {
if (state.hasNext()) {
downstream.push(mapper.apply(element, state.next()));
return true;
} else {
return false;
}
});
return new ZipIteratorGatherer<>(iterator, mapper);
}

public static <T, R> Gatherer<T, ?, R> zipWithIndex(BiFunction<Long, ? super T, ? extends R> mapper) {
Expand Down
33 changes: 33 additions & 0 deletions src/main/java/com/pivovarit/gatherers/ZipIteratorGatherer.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package com.pivovarit.gatherers;

import java.util.Iterator;
import java.util.Objects;
import java.util.function.BiFunction;
import java.util.function.Supplier;
import java.util.stream.Gatherer;

record ZipIteratorGatherer<T1, T2, R>(Iterator<T2> iterator, BiFunction<? super T1, ? super T2, ? extends R> mapper)
implements Gatherer<T1, Iterator<T2>, R> {

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

@Override
public Supplier<Iterator<T2>> initializer() {
return () -> iterator;
}

@Override
public Integrator<Iterator<T2>, T1, R> integrator() {
return (state, element, downstream) -> {
if (state.hasNext()) {
downstream.push(mapper.apply(element, state.next()));
return true;
} else {
return false;
}
};
}
}

0 comments on commit 6fb6341

Please sign in to comment.