Advertisement
Guest User

Untitled

a guest
Sep 21st, 2017
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.38 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. public static class Foo {
  4. private final int id;
  5. private final String name;
  6.  
  7. public Foo(int id, String name) { this.id = id; this.name = name; }
  8.  
  9. public int getId() { return id; }
  10. public String getName() { return name; }
  11.  
  12. @Override public String toString() { return "{id=" + id + "; name=" + name + "}";}
  13. }
  14.  
  15. public static class MyGroupingBy<U, V> implements
  16. Collector<U, Map<V, List<U>>, Map<V, List<U>>> {
  17.  
  18. private final Function<U, V> extractor;
  19.  
  20. public MyGroupingBy(Function<U, V> extractor) { this.extractor = extractor; }
  21.  
  22. @Override
  23. public BiConsumer<Map<V, List<U>>, U> accumulator() {
  24. return (map, obj) -> {
  25. System.out.println("accumulator " + map + " with " + obj);
  26. V key = extractor.apply(obj);
  27. if (!map.containsKey(key)) {
  28. map.put(key, Collections.singletonList(obj));
  29. } else {
  30. List<U> result = new ArrayList<>(map.get(key));
  31. result.add(obj);
  32. map.put(key, result);
  33. }
  34. };
  35. }
  36.  
  37. @Override
  38. public BinaryOperator<Map<V, List<U>>> combiner() {
  39. return (xs, ys) -> {
  40. System.out.println("combiner " + xs + " with " + ys);
  41.  
  42. Map<V, List<U>> res = new HashMap<>(xs);
  43.  
  44. ys.forEach((k, v) -> res.merge(k, v, (left, right) -> {
  45. List<U> combinedRes = new ArrayList<>(left);
  46. combinedRes.addAll(right);
  47. return combinedRes;
  48. }));
  49.  
  50. return res;
  51. };
  52. }
  53.  
  54. @Override
  55. public Supplier<Map<V, List<U>>> supplier() {
  56. System.out.println("supplier");
  57. return () -> new HashMap<>();
  58. }
  59.  
  60. @Override
  61. public Function<Map<V, List<U>>, Map<V, List<U>>> finisher() {
  62. System.out.println("finisher");
  63. return Function.identity();
  64. }
  65.  
  66. @Override
  67. public Set<Collector.Characteristics> characteristics() {
  68. System.out.println("characteristics");
  69. return Collections.singleton(Collector.Characteristics.IDENTITY_FINISH);
  70. }
  71. }
  72.  
  73. public static void main(String []args) {
  74. Function<Foo, String> extractor = Foo::getName;
  75. System.out.println(
  76. Stream.of(
  77. new Foo(1, "bar"),
  78. new Foo(2, "baz"),
  79. new Foo(3, "bar"),
  80. new Foo(4, "bar")
  81. ).collect(new MyGroupingBy(extractor))
  82. );
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement