-
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Introduce dedicated DistinctByKeepLastGatherer (#37)
- Loading branch information
Showing
2 changed files
with
39 additions
and
14 deletions.
There are no files selected for viewing
38 changes: 38 additions & 0 deletions
38
src/main/java/com/pivovarit/gatherers/DistinctByKeepLastGatherer.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} | ||
}; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters