How split arraylist to multiple lists by specific property object Java8 in one line

VitalyT :

Suppose I have

private String userId;
private String email;
private AWSRegion region;
private String total;
List<Prop> all = new ArrayList<>
all.add(new Prop("aaa", "dddd", "EU", total1));
all.add(new Prop("aaa1", "dddd", "US", tota2l));
all.add(new Prop("aaa2", "dddd", "AU", tota2l));
all.add(new Prop("aaa3", "dddd", "AU", tota3l));
all.add(new Prop("aaa3", "dddd", "EU", tota4l));....a lot of regions

I want in one line java8 to have list of lists by property "AWSRegion"

some think like....but not to run it as "filter predicate" because I have many of regions...

List<Prop> users = all.stream().filter(u -> u.getRegeion() == AWSRegion.ASIA_SIDNEY).collect(Collectors.toList());

RESULT should be list of lists:

LIST : {sublist1-AU , sublist2-US, sublist3-EU....,etc'}

thanks,

Eran :

Use groupingBy to get a Map<AWSRegion,List<Prop>> and then get the values of that Map:

Collection<List<Prop>> groups =
    all.stream()
       .collect(Collectors.groupingBy(Prop::getRegion))
       .values(); 

If the output should be a List, add an extra step:

List<List<Prop>> groups = new ArrayList<>(
    all.stream()
       .collect(Collectors.groupingBy(Prop::getRegion))
       .values()); 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=92922&siteId=1