Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java 8 list grouping with value mapping function producing list

I have a following Person class

public class Person {

    public String name;

    public List<Brand> brands;

    //Getters
}

and a List<Person> persons(possibly with same names). I need to group in a map of <String, List<Brand>> with Person's name as Keys and lists of accumulated Brands as values.

Something like this

 Map<String, List<List<String>>> collect = list.stream().collect(
        groupingBy(Person::getName, mapping(Person::getBrands, toList()))
 );

produces undesired result and I know why. If the values could be somehow flatten during grouping? Is there a way to do it right there with Streams api?

like image 891
srzhio Avatar asked Apr 15 '26 19:04

srzhio


1 Answers

java 9 will add the flatMapping collector specifically for this type of task:

list.stream().collect(
    groupingBy(
        Person::getName, 
        flatMapping(
            p -> p.getBrands().stream(), 
            toList()
        )
    )
like image 176
Misha Avatar answered Apr 18 '26 10:04

Misha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!