Skip to content

Commit

Permalink
Introduce dedicated DistinctByKeepLastGatherer (#37)
Browse files Browse the repository at this point in the history
  • Loading branch information
pivovarit authored Oct 14, 2024
1 parent a6986be commit 46d4256
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 14 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package com.pivovarit.gatherers;

import java.util.LinkedHashMap;
import java.util.Objects;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Gatherer;

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

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

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

@Override
public Integrator<LinkedHashMap<U, T>, T, T> integrator() {
return (state, element, _) -> {
state.put(keyExtractor.apply(element), element);
return true;
};
}

@Override
public BiConsumer<LinkedHashMap<U, T>, Downstream<? super T>> finisher() {
return (state, downstream) -> {
for (T element : state.values()) {
downstream.push(element);
}
};
}
}
15 changes: 1 addition & 14 deletions src/main/java/com/pivovarit/gatherers/MoreGatherers.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
import java.util.function.BiFunction;
Expand All @@ -24,19 +23,7 @@ private MoreGatherers() {
}

public static <T, U> Gatherer<T, ?, T> distinctByKeepLast(Function<? super T, ? extends U> keyExtractor) {
Objects.requireNonNull(keyExtractor, "keyExtractor can't be null");
return Gatherer.ofSequential(
LinkedHashMap<U, T>::new,
(state, element, _) -> {
state.put(keyExtractor.apply(element), element);
return true;
},
(state, downstream) -> {
for (T element : state.values()) {
downstream.push(element);
}
}
);
return new DistinctByKeepLastGatherer<>(keyExtractor);
}

public static <T, U> Gatherer<T, ?, T> distinctBy(Function<? super T, ? extends U> keyExtractor) {
Expand Down

0 comments on commit 46d4256

Please sign in to comment.