7

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,

2 Answers 2

8

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()); 
Sign up to request clarification or add additional context in comments.

Comments

2

You can create a map with <AWSRegion, List<Prop> by grouping your list by region:

Map<AWSRegion, List<Prop>> regionMap = all.stream()
   .collect(Collectors.groupingBy(Prop::getRegion, Collectors.toList()));

If you want that as a list, then you can simply call:

List<List<Prop>> lists = new ArrayList<>(regionMap.values());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.