java - 如何在一行中通过特定属性对象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'}
谢谢,
解决方案
用于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());
推荐阅读
- c - 如何将位填充到 C 中的字符串?
- c - 有人可以知道如何处理吗?
- spring-boot - 为什么 RemoteTokenServices 会频繁调用 UAA?
- c++ - 我如何在 c plus plus 中更改分配的类值
- python - 如何在 django html 中切片文本?
- xamarin - 如何记住选择器的选择,我使用 montemagno 的 xamarin.plugins.settings 并且我不知道如何获得正确的语法
- google-cloud-run - Cloud Scheduler 调用 Cloud Run 服务的身份验证
- node.js - 如何在单击按钮时生成校验和
- android - 错误:无法解决:com.android.support:appcompat-v7:29.0.0
- python - 为什么代码会打印两个答案,即使它们有不同的条件