Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- public static class Foo {
- private final int id;
- private final String name;
- public Foo(int id, String name) { this.id = id; this.name = name; }
- public int getId() { return id; }
- public String getName() { return name; }
- @Override public String toString() { return "{id=" + id + "; name=" + name + "}";}
- }
- public static class MyGroupingBy<U, V> implements
- Collector<U, Map<V, List<U>>, Map<V, List<U>>> {
- private final Function<U, V> extractor;
- public MyGroupingBy(Function<U, V> extractor) { this.extractor = extractor; }
- @Override
- public BiConsumer<Map<V, List<U>>, U> accumulator() {
- return (map, obj) -> {
- System.out.println("accumulator " + map + " with " + obj);
- V key = extractor.apply(obj);
- if (!map.containsKey(key)) {
- map.put(key, Collections.singletonList(obj));
- } else {
- List<U> result = new ArrayList<>(map.get(key));
- result.add(obj);
- map.put(key, result);
- }
- };
- }
- @Override
- public BinaryOperator<Map<V, List<U>>> combiner() {
- return (xs, ys) -> {
- System.out.println("combiner " + xs + " with " + ys);
- Map<V, List<U>> res = new HashMap<>(xs);
- ys.forEach((k, v) -> res.merge(k, v, (left, right) -> {
- List<U> combinedRes = new ArrayList<>(left);
- combinedRes.addAll(right);
- return combinedRes;
- }));
- return res;
- };
- }
- @Override
- public Supplier<Map<V, List<U>>> supplier() {
- System.out.println("supplier");
- return () -> new HashMap<>();
- }
- @Override
- public Function<Map<V, List<U>>, Map<V, List<U>>> finisher() {
- System.out.println("finisher");
- return Function.identity();
- }
- @Override
- public Set<Collector.Characteristics> characteristics() {
- System.out.println("characteristics");
- return Collections.singleton(Collector.Characteristics.IDENTITY_FINISH);
- }
- }
- public static void main(String []args) {
- Function<Foo, String> extractor = Foo::getName;
- System.out.println(
- Stream.of(
- new Foo(1, "bar"),
- new Foo(2, "baz"),
- new Foo(3, "bar"),
- new Foo(4, "bar")
- ).collect(new MyGroupingBy(extractor))
- );
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement