java8 lambda表达式集合操作常见用法大全

public static void main(String[] args) {
        // 先创建一个集合
        Cnblogs cnblogs = new Cnblogs();
        cnblogs.setId(1);
        cnblogs.setContext("dd");
        cnblogs.setTitle("DBC");

        Cnblogs cnblogs1 = new Cnblogs();
        cnblogs1.setId(3);
        cnblogs1.setContext("aa");
        cnblogs1.setTitle("ABC");

        Cnblogs cnblogs3 = new Cnblogs();
        cnblogs3.setId(4);
        cnblogs3.setContext("aa");
        cnblogs3.setTitle("ABC");

        Cnblogs cnblogs2 = new Cnblogs();
        cnblogs2.setId(2);
        cnblogs2.setContext("gg");
        cnblogs2.setTitle("VABC");
        List list = new ArrayList<>();
        List newList = new ArrayList<>();
        list.add(cnblogs);
        list.add(cnblogs1);
        list.add(cnblogs2);
        list.add(cnblogs3);

        /**
         * 1.遍历集合
         */
        list.stream().forEach(item->{

        });

        /**
         * 2.集合去重:单个字段(注意去重后是无序的)
         */
        newList = list.stream() .collect(
            Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(cn -> cn.getContext()))), ArrayList::new));

        /**
         * 2.集合去重:多个字段(注意去重后是无序的)
         */
        newList = list.stream() .collect(
            Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(cn -> cn.getContext() + cn.getId()))), ArrayList::new));

        /**
         * 3.根据对象属性排序((o1,o2)为升序,(o2,o1)为降序)
         */
        // 所比较的字段为字符串类型
        newList = list.stream().sorted((o1, o2) -> o1.getTitle().compareTo(o2.getTitle())).collect(Collectors.toList());
        // 所比较的字段为数字类型
        newList = list.stream().sorted((o1, o2) -> o1.getId() - (o2.getId())).collect(Collectors.toList());

        /**
         * 4.过滤
         */
        newList = list.stream().filter(item -> item.getId() > 3 && item.getTitle().equals("ABC")).collect(Collectors.toList());

        /**
         * 5.获取集合对象的某一属性返回一个新集合
         */
        List mapList2 = list.stream().map(item -> item.getTitle()).collect(Collectors.toList());

        /**
         * 6.统计
         */
        Integer sum = list.stream().mapToInt(Cnblogs::getId).sum();

        /**
         * 7.分组
         */
        Map> map = list.stream().collect(Collectors.groupingBy(Cnblogs::getContext));

        /**
         * 8.判断集合中是否存在某个值
         */
        boolean bool = list.stream().anyMatch(item -> item.getId() == 4 && item.getTitle().equals("ABC"));

        /**
         * 9.求集合中某个属性-最大值、最小值、和、平均值
         */
        IntSummaryStatistics stat = list.stream().mapToInt(item -> item.getId()).summaryStatistics();
        System.out.println("max:"+stat.getMax());
        System.out.println("min:"+stat.getMin());
        System.out.println("sum:"+stat.getSum());
        System.out.println("count:"+stat.getAverage());


    }

你可能感兴趣的:(java8 lambda表达式集合操作常见用法大全)