Skip to content

Commit

Permalink
Introduce dedicated DistinctByGatherer (#39)
Browse files Browse the repository at this point in the history
  • Loading branch information
pivovarit authored Oct 14, 2024
1 parent b583152 commit ef675c1
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 11 deletions.
29 changes: 29 additions & 0 deletions src/main/java/com/pivovarit/gatherers/DistinctByGatherer.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package com.pivovarit.gatherers;

import java.util.HashSet;
import java.util.Objects;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Gatherer;

record DistinctByGatherer<T, U>(Function<? super T, ? extends U> keyExtractor) implements Gatherer<T, HashSet<U>, T> {

DistinctByGatherer {
Objects.requireNonNull(keyExtractor, "keyExtractor can't be null");
}

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

@Override
public Integrator<HashSet<U>, T, T> integrator() {
return (state, element, downstream) -> {
if (state.add(keyExtractor.apply(element))) {
downstream.push(element);
}
return true;
};
}
}
12 changes: 1 addition & 11 deletions src/main/java/com/pivovarit/gatherers/MoreGatherers.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package com.pivovarit.gatherers;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Objects;
Expand All @@ -27,16 +26,7 @@ private MoreGatherers() {
}

public static <T, U> Gatherer<T, ?, T> distinctBy(Function<? super T, ? extends U> keyExtractor) {
Objects.requireNonNull(keyExtractor, "keyExtractor can't be null");
return Gatherer.ofSequential(
() -> new HashSet<U>(),
(state, element, downstream) -> {
if (state.add(keyExtractor.apply(element))) {
downstream.push(element);
}
return true;
}
);
return new DistinctByGatherer<>(keyExtractor);
}

public static <T> Gatherer<T, ?, T> distinctUntilChanged() {
Expand Down

0 comments on commit ef675c1

Please sign in to comment.