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,
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());
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());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.