Search code examples
javalambdajava-streamcollectors

How to collect a List<Foo> to a Map<Bar, List<Baz>> using Java lambdas?


I have an object Foo that has references to Bar and Baz objects:

public class Foo {
    private Bar bar;
    private Baz baz;

    public Foo(Bar bar, Baz baz) {
       this.bar = bar;
       this.baz = baz;
    }
}

I have a List<Foo> that I'd like to convert into a Map. I'd like the key to be Bar and the value to be a List<Baz>.

I can create a Map where Bar is the key and the value is a List<Foo>:

Map<Bar, List<Foo>> mapBarToFoos = foos.stream().collect(Collectors.groupingBy(Foo::getBar));

I don't know how to take that last step and turn the value List into a List<Baz>. Is there a lambda conversion on the value that I'm not seeing?


Solution

  • I think you want

    list.stream().collect(groupingBy(Foo::getBar, 
        mapping(Foo::getBaz, toList())));
    

    Where getBaz is the "downstream collector" which transforms the grouped Foos, then yet another which creates the list.