Java之Stream流的常用方法

流操作是Java8提供一个重要新特性,允许开发人员以声明性方式处理集合,其核心类库主要改进了对集合类的 API 和新增 Stream 操作。

一、流操作详解

图片

Stream流操作分为3种类型

  • 开始管道:获取一个stream

    API 功能说明
    stream() 创建出一个新的stream串行流对象
    parallelStream() 创建出一个可并行执行的stream流对象
    Stream.of() 通过给定的一系列元素创建一个新的Stream串行流对象
  • 中间管道:对Stream进行处理操作,并返回一个新的Stream对象,中间管道操作可以进行叠加。

    API 功能说明
    filter() 按照条件过滤符合要求的元素, 返回新的stream流
    map() 将已有元素转换为另一个对象类型,一对一逻辑,返回新的stream流
    flatMap() 将已有元素转换为另一个对象类型,一对多逻辑,即原来一个元素对象可能会转换为1个或者多个新类型的元素,返回新的stream流
    limit() 仅保留集合前面指定个数的元素,返回新的stream流
    skip() 跳过集合前面指定个数的元素,返回新的stream流
    concat() 将两个流的数据合并起来为1个新的流,返回新的stream流
    distinct() 对Stream中所有元素进行去重,返回新的stream流
    sorted() 对stream中所有的元素按照指定规则进行排序,返回新的stream流
    peek() 对stream流中的每个元素进行逐个遍历处理,返回处理后的stream流
  • 终止管道:终止Stream流,执行操作。

    API 功能说明
    count() 返回stream处理后最终的元素个数
    max() 返回stream处理后的元素最大值
    min() 返回stream处理后的元素最小值
    findFirst() 找到第一个符合条件的元素时则终止流处理
    findAny() 找到任何一个符合条件的元素时则退出流处理,这个对于串行流时与findFirst相同,对于并行流时比较高效,任何分片中找到都会终止后续计算逻辑
    anyMatch() 返回一个boolean值,类似于isContains(),用于判断是否有符合条件的元素
    allMatch() 返回一个boolean值,用于判断是否所有元素都符合条件
    noneMatch() 安徽一个boolean值, 用于判断是否所有元素都不符合条件
    collect() 将流转换为指定的类型,通过Collectors进行指定
    toArray() 将流转换为数组
    iterator() 将流转换为Iterator对象
    foreach() 无返回值,对元素进行逐个遍历,然后执行给定的处理逻辑

二、Stream API 用法

https://gitee.com/kk-dad/jdk8_stream_demo

点击查看代码
    public static void main(String[] args) throws IOException {
        ArrayList<Student> students = new ArrayList<>();
        students.add(new Student(1, 19, "张三", "A", true));
        students.add(new Student(1, 20, "张三", "A", true));
        students.add(new Student(1, 18, "李四", "a", false));
        students.add(new Student(1, 21, "王五", "B", true));
        students.add(new Student(1, 20, "赵六", "b", false));
        students.add(new Student(1, 20, "赵六", "F", false));
        students.add(new Student(1, 20, "赵六", "F", false));
        students.add(new Student(1, 20, "赵六", "F", false));

        // 1.中间管道 filter 过滤,终止管道 forEach 遍历
        System.out.println("// 1.中间管道 filter 过滤,终止管道 forEach 遍历");
        students.stream()
                .filter(student -> student.getAge() < 20)
                .forEach(System.out::println);

        // 2.collect 收集
        System.out.println("\n// 2.collect 收集");
        List<Student> list = students.stream()
                .filter(student -> student.getAge() <= 20)
                .collect(Collectors.toList());
        System.out.println(list);
        Set<Student> set = students.stream()
                .filter(student -> student.getAge() < 20)
                .collect(Collectors.toSet());
        System.out.println(set);

        // 3.distinct 去重
        System.out.println("\n// 3.distinct 去重");
        List<Student> studentList = students.stream()
                .distinct()
                .collect(Collectors.toList());
        System.out.println(studentList);


        List<String> ids = Arrays.asList("234","100","200","305");
        // 4.map 一对一转换.
        System.out.println("\n// 4.map 一对一转换.");
        List<Integer> results = ids.stream()
                .map(Integer::valueOf)
                .collect(Collectors.toList());
        System.out.println(results);

        List<String> sentences = Arrays.asList(" hello world","Jia Gou Wu Dao ","a", "b");
        // 5.flatMap 一对多转换.
        System.out.println("\n// 5.flatMap 一对多转换.");
        List<String> r = sentences.stream()
                .flatMap(sentence -> Arrays.stream(sentence.split(" ")))
                .collect(Collectors.toList());
        System.out.println(r);

        // 6.peek中间管道,对stream中的每个元素逐个遍历处理,中间管道必须搭配终止管道一起使用,否则中间管道的操作不会执行。
        System.out.println("\n// 6.peek中间管道,对stream中的每个元素逐个遍历处理,中间管道必须搭配终止管道一起使用,否则中间管道的操作不会执行。");
        sentences.stream().filter(s -> {
            System.out.println(s);
            return s.contains("hello");
        }).forEach(System.out::println);
        sentences.stream()
                .peek(System.out::println);
        sentences.stream()
                .peek(System.out::println)
                .forEach(System.out::println);


        // 7.List或者数组中的值拼接到一个字符串里并以逗号分隔开, Collectors.joining
        System.out.println("\n// 7.List或者数组中的值拼接到一个字符串里并以逗号分隔开, Collectors.joining");
        String toOneString = ids.stream()
                .collect(Collectors.joining(","));
        System.out.println(toOneString);

        // 8.Collectors.averagingInt, 求集合均值
        System.out.println("\n // 8.Collectors.averagingInt, 求集合均值");
        Double collect = ids.stream()
                .map(Integer::parseInt)
                .collect(Collectors.averagingInt(value -> value));
        System.out.println(collect);

        // 9.统计信息, Collectors.summarizingInt
        System.out.println("\n // 9.统计信息, Collectors.summarizingInt");
        IntSummaryStatistics summaryStatistics = ids.stream()
                .collect(Collectors.summarizingInt(Integer::parseInt));
        System.out.println(summaryStatistics);

        // 10.Collectors.groupingBy
        System.out.println("\n// 10.Collectors.groupingBy");
        Map<Object, Map<Object, List<Student>>> collect1 = students.stream()
                .collect(Collectors.groupingBy(Student::getSex, Collectors.groupingBy(Student::getName)));
        System.out.println(collect1);

        // 11.sorted排序, 默认升序,可自定义排序规则。
        System.out.println("\n// 11.sorted排序, 默认升序,可自定义排序规则.");
        System.out.println("根据sex升序");
        List<Student> collect2 = students.stream()
                .distinct()
                .sorted( Comparator.comparing(student -> student.getSex()))
                .collect(Collectors.toList());
        System.out.println(collect2);

        //但是这样有点不好,因为是先排序然后在逆序的,要两步操作。
        System.out.println("reversed, 根据sex降序,//但是这样有点不好,因为是先排序然后在逆序的,要两步操作。");
        List<Student> collect3 = students.stream()
                .distinct()
                .sorted( Comparator.comparing(Student::getSex).reversed())
                .collect(Collectors.toList());
        System.out.println(collect3);
        // reverseOrder 同 reversed 一样,需要两步操作。
        System.out.println("// reverseOrder 同 reversed 一样,需要两步操作");
        List<Student> collect4 = students.stream()
                .distinct()
                .sorted( Comparator.comparing(Student::getSex, Comparator.reverseOrder()))
                .collect(Collectors.toList());
        System.out.println(collect4);

        System.out.println("// sex age 多级排序");
        List<Student> collect44 = students.stream()
                .distinct()
                .sorted(Comparator.comparing(Student::getSex).thenComparing(Student::getAge, Comparator.reverseOrder()))
                .collect(Collectors.toList());
        System.out.println(collect44);

        // o1-o2 升序, o2-o1 降序
        System.out.println("\n// 在sorted中自定义排序规则.");
        List<Student> collect5 = students.stream()
                .distinct()
                .sorted((o1, o2) -> o2.getAge() - o1.getAge())
                .collect(Collectors.toList());
        System.out.println(collect5);

        // 字典顺序排序
        System.out.println("\n// 字典顺序.");
        List<Student> collect55 = students.stream()
                .distinct()
                .sorted((o1, o2) -> {
                    try {
                        String str1 = new String(o1.getName().getBytes("GB2312"), StandardCharsets.ISO_8859_1);
                        String str2 = new String(o2.getName().getBytes("GB2312"), StandardCharsets.ISO_8859_1);
                        return str1.compareTo(str2);
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }

                    return 0;
                })
                .collect(Collectors.toList());
        System.out.println(collect55);

        File file = new File("a.txt");
        File file1 = new File("b.txt");
        List<String> list1 = Files.readAllLines(Paths.get("a.txt"));
        List<String> list2 = Files.readAllLines(Paths.get("b.txt"));


        // 文件内容比较
        System.out.println("// 文件内容比较");
        List<String> collect6 = list1.stream()
                .filter(s -> list2.stream().noneMatch(s1 -> s1.trim().equals(s.trim())))
                .collect(Collectors.toList());
        System.out.println("old:" + collect6 + "已删除");

        List<String> collect7 = list2.stream()
                .filter(s -> list1.stream().noneMatch(s1 -> s1.trim().equals(s.trim())))
                .collect(Collectors.toList());
        System.out.println("new:" + collect7 + "新增");
    }
posted @   little_lunatic  阅读(241)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 什么是nginx的强缓存和协商缓存
· 一文读懂知识蒸馏
· Manus爆火,是硬核还是营销?
历史上的今天:
2021-07-12 yum安装redis
2021-07-12 yum安装mysql5.7和8.0版本
点击右上角即可分享
微信分享提示