首页 > 其他分享 >stream流根据一个字段分组同时提取另一字段

stream流根据一个字段分组同时提取另一字段

时间:2022-09-23 17:15:55浏览次数:52  
标签:String stream aaaa phone 一字段 分组 Test message

//测试类部分
class Test{
private String phone;

private String message;

public String getPhone() {
return phone;
}

public void setPhone(String phone) {
this.phone = phone;
}

public String getMessage() {
return message;
}

public void setMessage(String message) {
this.message = message;
}
}

// 模拟数据
List<Test> arr = new ArrayList<>();
for (int i = 0; i < 10; i++) {
Test s = new Test();
if (i<5){
s.setPhone("1111");
}else {
s.setPhone("2222");
}
s.setMessage("aaaa");
arr.add(s);
}
// stream流
Map<String, List<String>> collect = arr.stream().collect(Collectors.groupingBy(Test::getPhone, Collectors.mapping(Test::getMessage, Collectors.toList())));

输出结果
{2222=[aaaa, aaaa, aaaa, aaaa, aaaa], 1111=[aaaa, aaaa, aaaa, aaaa, aaaa]}

标签:String,stream,aaaa,phone,一字段,分组,Test,message
From: https://www.cnblogs.com/DarkerbeS/p/16723397.html

相关文章