Java list stream的简单使用

分组

// Collectors.groupingBy 此处是根据Student对象的classId进行分组
Map<String, List<Student>> collect = stuList.stream().collect(Collectors.groupingBy(Student::getClassId));
     for(Map.Entry<String, List<Student>> stuMap:collect.entrySet()){
          String classId = stuMap.getKey();
          List<Student> studentList = stuMap.getValue();
          System.out.println("classId:"+classId+",studentList:"+studentList.toString());
     }}
     collect.for((k,v) -> {
     	String classId = k;
        List<Student> studentList = v;
        System.out.println("classId:"+classId+",studentList:"+studentList.toString());
     })
     
 // Collectors.toMap
 // key 与 value 都必须唯一,如果存在多个value 可以使用Collectors.groupingBy
 Map<String, Long> shiftDateQtyMap = hmeLineShiftProgressVO4s.stream().collect(Collectors.toMap(HmeLineShiftProgressVO4::getShiftDate, HmeLineShiftProgressVO4::getQty));

排序

// 默认升序排序,排序时建议使用基本数据类型
exceptionVoList.stream().sorted(Comparator.comparing(HmeExceptionHandlePlatFormVO::getOrderBy)).collect(Collectors.toList());

// 多重排序 使用 thenComparing 在根据选择属性进行排序,与sql排序同理, reversed() 对当前排序字段进行反转;
resultList.stream().sorted(Comparator.comparing(HmeCompletedAttachmentVO3::getSeq)
            .thenComparing(HmeCompletedAttachmentVO3::getCreationDate).reversed()).collect(Collectors.toList());

// 根据map 的key进行排序
Map<Date, List<HmePreprocessWorkcellVO>> collect =workcellVOS.stream().collect(Collectors.groupingBy(HmePreprocessWorkcellVO::getCreationDate));
// 升序
collect.entrySet().stream().sorted(Map.Entry.comparingByKey());

筛选

List.stream().filter(item ->
    respondEmployeeId.equals(item.getRespondEmployeeId())
   ).findAny().isPresent()

去重

list.stream().distinct();// 只能对单个类型的集合进行去重

计算

// 使用 BigDecimal 求和
BigDecimal qtySum = dto1.getDetailDTOList().stream().map(t -> BigDecimal.valueOf(t.getPrimaryUomQty())).reduce(BigDecimal.ZERO, BigDecimal::add);

ist.stream().mapToDouble(User::getHeight).sum()//和 不建议使用,Double会丧失精度
list.stream().mapToDouble(User::getHeight).max()//最大
list.stream().mapToDouble(User::getHeight).min()//最小
list.stream().mapToDouble(User::getHeight).average()//平均值

// 使用AtomicInteger获取对应的下标
list.add("test1");
list.add("test2");
list.add("test3");
AtomicInteger index = new AtomicInteger(0);
list.stream()
     //指定匹配逻辑
     filter(s -> {
            //每比对一个元素,数值加1
            index.getAndIncrement();
            return s.equals("test2");
        })
        .findFirst();
    System.out.println(index.get());
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值