首页 > 解决方案 > 如何在一行中通过特定属性对象Java8将arraylist拆分为多个列表

问题描述

假设我有

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

我希望在一行java8中按属性“AWSRegion”列出列表

有些人认为......但不要将其作为“过滤谓词”运行,因为我有很多地区......

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

RESULT 应该是列表列表:

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

谢谢,

标签: javajava-8

解决方案


用于groupingBy获取 aMap<AWSRegion,List<Prop>>然后获取 that 的值Map

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

如果输出应该是 a List,请添加一个额外的步骤:

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

推荐阅读