From 46d425603bc4aa6613a816283e895ae5bde7035b Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Mon, 14 Oct 2024 20:19:24 +0200 Subject: [PATCH] Introduce dedicated DistinctByKeepLastGatherer (#37) --- .../gatherers/DistinctByKeepLastGatherer.java | 38 +++++++++++++++++++ .../pivovarit/gatherers/MoreGatherers.java | 15 +------- 2 files changed, 39 insertions(+), 14 deletions(-) create mode 100644 src/main/java/com/pivovarit/gatherers/DistinctByKeepLastGatherer.java diff --git a/src/main/java/com/pivovarit/gatherers/DistinctByKeepLastGatherer.java b/src/main/java/com/pivovarit/gatherers/DistinctByKeepLastGatherer.java new file mode 100644 index 0000000..0f7f88b --- /dev/null +++ b/src/main/java/com/pivovarit/gatherers/DistinctByKeepLastGatherer.java @@ -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( + Function keyExtractor) implements Gatherer, T> { + + DistinctByKeepLastGatherer { + Objects.requireNonNull(keyExtractor, "keyExtractor can't be null"); + } + + @Override + public Supplier> initializer() { + return LinkedHashMap::new; + } + + @Override + public Integrator, T, T> integrator() { + return (state, element, _) -> { + state.put(keyExtractor.apply(element), element); + return true; + }; + } + + @Override + public BiConsumer, Downstream> finisher() { + return (state, downstream) -> { + for (T element : state.values()) { + downstream.push(element); + } + }; + } +} diff --git a/src/main/java/com/pivovarit/gatherers/MoreGatherers.java b/src/main/java/com/pivovarit/gatherers/MoreGatherers.java index 1ef38e2..801f654 100644 --- a/src/main/java/com/pivovarit/gatherers/MoreGatherers.java +++ b/src/main/java/com/pivovarit/gatherers/MoreGatherers.java @@ -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; @@ -24,19 +23,7 @@ private MoreGatherers() { } public static Gatherer distinctByKeepLast(Function keyExtractor) { - Objects.requireNonNull(keyExtractor, "keyExtractor can't be null"); - return Gatherer.ofSequential( - LinkedHashMap::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 Gatherer distinctBy(Function keyExtractor) {