org.agzamovr.collectors.DistinctCollector Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of collectorex Show documentation
Show all versions of collectorex Show documentation
Java Collectors extensions for using with Java 8 streams
The newest version!
package org.agzamovr.collectors;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collector;
class DistinctCollector {
static final DistinctCollector DISTINCT_COLLECTOR = new DistinctCollector();
R distinctFinisher(Map map,
Collector super T, ?, R> downstream) {
return map.values().stream().collect(downstream);
}
void accumulator(Map map, T item, Function super T, D> mapper) {
map.put(mapper.apply(item), item);
}
Map combiner(Map left, Map right) {
left.putAll(right);
return left;
}
Collector, Collection> distinct(Function super T, D> mapper) {
return Collector.of(HashMap::new,
(map, item) -> accumulator(map, item, mapper),
this::combiner,
Map::values);
}
Collector, R> distinct(Function super T, D> mapper,
Collector super T, ?, R> downstream) {
return Collector.of(HashMap::new,
(map, item) -> accumulator(map, item, mapper),
this::combiner,
(map) -> distinctFinisher(map, downstream));
}
}