distinctBy()
Filter a stream such that it only contains distinct elements measured by the given
mappingFunction.Implementation Notes
This gatherer uses Object::equals() to measure equality of objects returned from the mappingFunction. Encounter
order is preserved, so the first instance of a non-distinct element is the one that will be emitted to the output stream.
For a version of this function that measures distinctiveness based on Object::equals() alone, see the
Stream::distinct()in the JDK.
See also uniquelyOccurring() which emits elements that only exist once in the input stream.
Signature
distinctBy(Function<INPUT, Object> mappingFunction)
mappingFunction- A non-null function to mapINPUTtypes to an arbitraryObjectto use for comparison
Examples
Filter objects distinctly by a specific property
record Person(String firstName, String lastName) {}
Stream
.of(
new Person("Todd", "Ginsberg"),
new Person("Emma", "Ginsberg"),
new Person("Todd", "Smith")
)
.gather(Gatherers4j.distinctBy(Person::firstName))
.toList();
// [Person("Todd", "Ginsberg"), Person("Emma", "Ginsberg")]