javatreemapgroupingby

stream of list groupinngBy to map


the example code I've been given is

public Map<String, List<Bier>> opzettenOverzichtBierenPerSoort() {
   //TODO
    
    return bieren.stream().collect(Collectors.groupingBy(Bier::getSoort, TreeMap::new, Collectors.toList()));
}

input is a list of beer objects and it return a map of the kind of beer with all the beers in it.

now my question. wat are the second and third arguments in the groupingBy? I get the first one which states what it's grouped by...but the second and third seem a bit random.


Solution

  • The second argument is a Supplier<M>, which is used to produce a Map instance.

    The third argument is a downstream Collector, which specifies what to do with the Bier elements which belong to a single group.

    If you run the single argument variant:

    return bieren.stream().collect(Collectors.groupingBy(Bier::getSoort));
    

    It will still collect the elements of each group into a List (that's the default behavior), but you don't have control over the type of Map that will map the String keys into the corresponding Lists.

    In your 3 argument example, you request that the Map will be a TreeMap, which means the keys will be sorted.

    The current implementation of the single argument variant:

    return bieren.stream().collect(Collectors.groupingBy(Bier::getSoort));
    

    is equivalent to:

    return bieren.stream().collect(Collectors.groupingBy(Bier::getSoort, HashMap::new, Collectors.toList()));
    

    which means the keys of the Map will not be sorted.