java8 stream流操作


// 利用stream流中的TreeSet去重
		List<ResourceTaskWhiteListVo> distinctWhiteList = whiteListVoList.stream()
				.collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.getEnv() + "|" + o.getShortName() + "|" + o.getSoftwareType() + "|" + o.getInstanceCode() ))), ArrayList::new));

// 获取空字符串的数量
        List<String> strings1 = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
        long count = strings1.parallelStream().filter(string -> string.isEmpty()).count();

// list转为map
        Map<String,Object> map = person.stream().collect(Collectors.toMap(Person::getName,Person::getAge));

//获取实体类list中的某一字段值
        List<String> listString = resourceRuleTaskDetailList.stream().map(ResourceRuleTaskDetail::getSystemEnName).collect(Collectors.toList());
        List<String> listString1 = resourceRuleTaskDetailList.stream().map(s -> s.getSystemEnName()).collect(Collectors.toList());

        //输出列表中最大的数
        //1.写法一
        LongSummaryStatistics stats = resourceRuleTaskDetailList.stream().mapToLong(s -> s.getTaskId()).summaryStatistics();

        //写法二
        Long min = resourceRuleTaskDetailList.stream().mapToLong(s -> s.getTaskId()).min().getAsLong();
        Long max = resourceRuleTaskDetailList.stream().mapToLong(s -> s.getTaskId()).max().getAsLong();
        Long sum = resourceRuleTaskDetailList.stream().mapToLong(s -> s.getTaskId()).sum();
        Double avg = resourceRuleTaskDetailList.stream().mapToLong(s -> s.getTaskId()).average().getAsDouble();

 //按照taskId分组,并取第一条数据
        Map<Long,ResourceManageTaskHistory> taskHistoryMap = historyList.stream().collect(Collectors.groupingBy(ResourceManageTaskHistory::getTaskId, Collectors.collectingAndThen(Collectors.toList(), value -> value.get(0))));
        // map转为list
        List<ResourceManageTaskHistory> taskHistoryList = taskHistoryMap.entrySet().stream().map(en -> en.getValue()).collect(Collectors.toList());

 //过滤白名单系统信息
        List<String> systemWhiteEnNameList = Arrays.asList("abc", "asd", "bc", "efg", "abcd","", "jkl");
        List<ResourceRuleTaskDetail> filter = resourceRuleTaskDetailList.stream().filter(s -> !systemWhiteEnNameList.contains(s.getSystemEnName())).collect(Collectors.toList());

 // 交集
        List<String> intersection = list1.stream().filter(item -> list2.contains(item)).collect(Collectors.toList());

 // 差集 (list1 - list2)
        List<String> reduce1 = list1.stream().filter(item -> !list2.contains(item)).collect(Collectors.toList());

 // 差集 (list2 - list1)
        List<String> reduce2 = list2.stream().filter(item -> !list1.contains(item)).collect(Collectors.toList());

 // 并集
        List<String> listAll = list1.parallelStream().collect(Collectors.toList());
        List<String> listAll2 = list2.parallelStream().collect(Collectors.toList());
        listAll.addAll(listAll2);
posted @ 2021-04-30 17:28  王岳阳  阅读(155)  评论(0编辑  收藏  举报