java8 lambda 表达式的应用关于list与map的转换和对象集合排序

1.List转为map (适用于统计数量或List中有两个字段值的转换)注(第一个取值为key,第二个为value)
Map map = list.stream().collect(Collectors.toMap(s->s.get("route_code"), s -> s.get("COUNT")));
2.通过对象集合里的某一属性排序u1在前为正序u2在前为倒序
List objs= logisticsRouteExtends.stream().sorted((u1, u2) -> u2.getNumbers().compareTo(u1.getNumbers())).collect(Collectors.toList());

3.取出一个对象集合里某个字段的值

List groupCodes = list.stream().map(p -> p.getDispatchingGroupCode()).collect(Collectors.toList());

List goodsCodes = dispatchingPowers.stream().map(LogisticsDispatchingPower::getGoodsCode).collect(Collectors.toList());

4.对象集合根据某个字段去重

logisticsDispatchingUsers = logisticsDispatchingUsers.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(LogisticsDispatchingUser::getDispatchingGroupCode))), ArrayList::new));

5.统计List数量为Map(为null会抛异常,先转为空串)

Map map = list.stream().
        collect(Collectors.groupingBy(java.util.function.Function.identity(),Collectors.counting()));

6.通过字符串集合去除一个对象集合里对象某个属性值中字符串集合包含的对应的对象

custLimitSets =  custLimitSets.stream().filter(custLimitSet -> ! strings.contains(custLimitSet.getCustNo())).collect(Collectors.toList());(strings中空串和null也能去除)

7.字符串集合中去除null和空或字段

List strings = new ArrayList<>();
strings.add(null);
strings.add("");list = list.stream().filter(s -> !strings.contains(s) ).collect(Collectors.toList());

8.求和

//基本类型
        int sum = userList.stream().mapToInt(User::getAge).sum();
        //BigDecimal求和  BigDecimal invoiceAmount = wholesaleBillVos.stream().map(WholesaleBillVo::getSaleAmount).reduce(BigDecimal.ZERO, BigDecimal::add);

 

你可能感兴趣的:(java8 lambda 表达式的应用关于list与map的转换和对象集合排序)