Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java8 - groupingby from a property inside an object

I want to create a Map<String,List<A>> where A contains B and the groupby is made from a property from B.

public class A{
        private int a;
        private ...
        private B b;
}

public class B{
           private String name;
           private ... 
}

and I have a

List<A> alist;

and I want to do something like that :

Map<String, List<A>> resultmap = alist.stream().collect(Collectors.groupingby(B::getName()));

except this is not possible to access B.

like image 981
Thomas Laforge Avatar asked Feb 23 '16 11:02

Thomas Laforge


2 Answers

You just need to write a lambda expression to access b:

Map<String, List<A>> resultMap = alist.stream()
                                      .collect(Collectors.groupingBy(a -> a.getB().getName()));

Assuming there is a getter getB() to retrieve the b property, you can call that inside the lambda expression.


As a side-note, your current method-reference is invalid: you don't need the parentheses inside B::getName().

like image 165
Tunaki Avatar answered Nov 11 '22 18:11

Tunaki


You can do this with a lambda expression instead of a method reference :

Map<String, List<A>> resultmap =     
    alist.stream().collect(Collectors.groupingby(a->a.getB().getName()));
like image 6
Eran Avatar answered Nov 11 '22 19:11

Eran