Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8207956

Three argument Collectors.groupingBy is not completely correct and needs clarification in documentation

XMLWordPrintable

      A DESCRIPTION OF THE PROBLEM :
      Collectors.groupingBy(3 arg) assumes `mapFactory` returns a `Map` where all values can be stored if collector isn't an identity collector. This isn't part of `Map` interface, it's allowed by the language to make maps that only work with certain return values. This isn't documented.


      ---------- BEGIN SOURCE ----------
      import java.util.HashMap;
      import java.util.Map;
      import java.util.function.Supplier;
      import java.util.stream.Stream;

      import static java.util.Collections.checkedMap;
      import static java.util.stream.Collectors.*;

      public class Example {
          public static void main(String[] args) {
              Supplier<Map<String, String>> mapSupplier = () -> checkedMap(new HashMap<>(), String.class, String.class);
              Map<String, String> result = Stream.of("a", "b").collect(groupingBy(x -> x, mapSupplier, collectingAndThen(toList(), x -> x.get(0))));
              System.out.println(result);
          }
      }
      ---------- END SOURCE ----------

      FREQUENCY : always


            vklang Viktor Klang
            webbuggrp Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            5 Start watching this issue

              Created:
              Updated: