JDK8 Stream 常见应用

一、双循环遍历:

例:

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

二、去重

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

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

3、针对 Map:
    List> 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> result) {
        if (!StringUtils.isEmpty(cloudRInfoPo.getDuration()) || "desc".equals(cloudRInfoPo.getSort())) {
            result.sort(Comparator.comparing((Map h) -> ((String) h.get("lastOnlineTime"))));  //正序
        }
        if (!StringUtils.isEmpty(cloudRInfoPo.getDuration()) || "asc".equals(cloudRInfoPo.getSort())) {
            result.sort(Comparator.comparing((Map h) -> ((String) h.get("lastOnlineTime"))).reversed()); //倒序
        }
    }

你可能感兴趣的:(Java,Stream,java基础,java)