1.list 过滤 --得到和map匹配的list
List<CustInfo> custInfoList = tmpList.stream().filter(t -> map.containsKey(t.CustNo)).collect(Collectors.toList());
2.分组求和 --根据custNo和sellCodeNo 分组,对money求和 得到一个map
Map<String,Double> tmpMap = new HashMap<>();
tmpMap = orderList.stream().collect(Collectors.groupingBy(
t -> t.custNo + '-' + t.sellCodeNo , Collectors.summingDouble(t -> t.money)));
3.提取List中一个或多个字段并去重
List<String> orderList = tmpList.stream().map(t -> t.custNo + '-' + t.orderSno).distinct().collect(Collectors.toList());
4.对List多个字段分组
Map<String, List<Order>> orderMap = tmpList.stream.collect(Collectors.groupingBy(
t -> t.custNo + '-' + t.sellCodeNo)
5.List转Map
Map<String,User> maps = custInfoList.stream.collect(Collectors.toMap(User::getId,user -> user));
Map<String,User> maps = custInfoList.stream.collect(Collectors.toMap(User::getId,Function.identity(),(key1,key2) -> key2));
//key重复需要指定第三个参数
6.根据多个字段分组,取每组最大
Map<String,User> Map = List.stream().collect(
Collectors.groupingBy(t -> t.custid + '-' + t.name,
Collectors.collectingAndThen(
Collectors.reducing((nav1,nav2) -> 2>1 ? 2 : 1), Optional::get
)
)
);
本文介绍了Java中使用Stream API进行数据处理的各种方法,包括List过滤、分组求和、提取字段去重、多字段分组、List转Map以及根据多字段分组取最大值的操作。这些技巧在处理集合数据时非常实用,能有效提高代码的简洁性和效率。
1169

被折叠的 条评论
为什么被折叠?



