JDK8 Stream 常见应用

一、双循环遍历:

例:

ListOne.stream().forEach(one -> ListTwo.stream().anyMatch(two->{
            // 处理业务逻辑
              ......
            return false;
        }));

二、去重

1、针对 对象 一个字段:
ArrayList<ProductProcessDrawbackDto> collect = records1.stream().collect(Collectors.collectingAndThen(
                        Collectors.toCollection(() -> new TreeSet<>(
                                Comparator.comparing(
                                        ProductProcessDrawbackDto::getId))), ArrayList::new));

2、针对 对象 多个字段:
 ArrayList<PatentDto> collect1 = patentDtoList.stream().collect(Collectors.collectingAndThen(
                Collectors.toCollection(() -> new TreeSet<>(
                        Comparator.comparing(p->p.getPatentName() + ";" + p.getLevel()))), ArrayList::new);

3、针对 Map:
    List<Map<String, Object>> list2 = list1.stream().collect(
               Collectors.collectingAndThen(
                       Collectors.toCollection(
                               () ->new TreeSet<>(Comparator.comparing(m->m.get("value").toString()))
                       ),ArrayList::new
               )
       );

三、排序

1、使用sort

// 倒序
##写法1
list = list.stream()
                .sorted(Comparator.comparing(Test::getAge).reversed())
                .collect(Collectors.toList());
##写法2
list = list.stream()
                .sorted(Comparator.comparing(Test::getAge, Comparator.reverseOrder()))
                .collect(Collectors.toList());
### 简洁
list.stream().sorted(Comparator.comparing(Test::getAge, Comparator.reverseOrder()));

## 多个字段 倒序 用.thenComparing()拼接到后面
list.stream().sorted(Comparator.comparing(Test::getAge).thenComparing(Test::getState).reversed());

// 升序
##不加reversed即可,默认就是升序

2、List(Map)进行Stream排序

public void sortLastOnlineList(CloudRInfoPo cloudRInfoPo, List<Map<String, Object>> result) {
        if (!StringUtils.isEmpty(cloudRInfoPo.getDuration()) || "desc".equals(cloudRInfoPo.getSort())) {
            result.sort(Comparator.comparing((Map<String, Object> h) -> ((String) h.get("lastOnlineTime"))));  //正序
        }
        if (!StringUtils.isEmpty(cloudRInfoPo.getDuration()) || "asc".equals(cloudRInfoPo.getSort())) {
            result.sort(Comparator.comparing((Map<String, Object> h) -> ((String) h.get("lastOnlineTime"))).reversed()); //倒序
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值