stream的使用

文章介绍了如何使用JavaStreamAPI进行数据处理,包括针对特定属性去重,排除空值,对列表进行排序(考虑null值的情况),以及多条件排序。同时展示了如何使用stream进行列表的分组和元素转换。
摘要由CSDN通过智能技术生成

一.对象针对某个属性去重

SysEntertainSchemeStandardDTOList = lstDTO.stream().filter(e -> e.getEntertainLevel()!=null && e.getEntertainLevel()!="").collect(
        Collectors.collectingAndThen(Collectors.toCollection(() ->
                new TreeSet<>(Comparator.comparing( u-> u.getEntertainLevel()))), ArrayList::new));

二.对某个值去重并且排除为空的

operatorUserIds = memberEntityList.stream().map(FscFgMemberEntity::getOperatorUserId).filter(StrUtil::isNotBlank).distinct().collect(Collectors.toList())

三.使用stream对list集合排序

方法一 : 使用 Stream 进行排序时,如果排序的字段出现 null 值就会导致异常发生

 list = list.stream().sorted(Comparator.comparing(Person::getAge).reversed())
        .collect(Collectors.toList())

方法二:Comparator.nullsFirst 表示将排序字段中的 null 值放到集合最前面,如果想要将 null 值放到集合最后面可以使用 Comparator.nullsLast

list = list.stream().sorted(Comparator.comparing(Person::getAge,
        Comparator.nullsFirst(Integer::compareTo)))
        .collect(Collectors.toList());

四.使用stream进行排序

按照List中对象的id属性升序

list.sort(Comparator.comparing(Stu::getId))

按照List中对象的id属性降序

list.sort(Comparator.comparing(Stu::getId).reversed());

多条件升序

list.sort(Comparator.comparing(Stu::getId).thenComparing(Stu::getSid));

多条件降序

list.sort(Comparator.comparing(Stu::getId).reversed().thenComparing(Stu::getSid))

分组

Map<String, List<OpEfsPaymentDTO>> collect = dtoList.stream().collect(Collectors.groupingBy(
        OpEfsPaymentDTO::getBoeHeaderId));

stream遍历重新赋值

private List<Application> buildApplications(List<ApplicationDTO> dtoList, Long collectionId) {
        return dtoList.stream().map(p -> buildApplicationByDto(p, collectionId)).collect(Collectors.toList());
    }
    private Application buildApplicationByDto(ApplicationDTO dto, Long collectionId) {
        Application application = new Application();
        application.setCollectionId(collectionId);
        application.setAppType(dto.getAppType());
        application.setPaper(dto.getPaper());
        application.setCopies(dto.getCopies());
        application.setPlateNo(dto.getPlateNo());
        application.setVehId(dto.getVehId());;
        return application;
    }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值