• 学习Java8 Stream流,让我们更加便捷的操纵集合


    1. 概述

    本篇文章会简略的介绍一下 Lambda 表达式,然后开启我们的正题 Java8 Stream 流,希望观众老爷们多多支持,并在评论区批评指正!

    Java8Stream 流使用的是函数式编程模式。它可以被用来对集合或数组进行链状流式的操作,可以更方便的让我们对集合或数组操作。

    2. Stream流为什么操作集合便捷?

    Stream流为什么操作集合便捷?我们通过一个小例子来演示一下:

    首先我们创建一个类,准备一些数据用于演示:

    1. public class StreamDemo {
    2. private static List<Author> getAuthors() {
    3. //数据初始化
    4. Author author = new Author(1L,"蒙多",33,"一个从菜刀中明悟哲理的祖安人",null);
    5. Author author2 = new Author(2L,"亚拉索",15,"狂风也追逐不上他的思考速度",null);
    6. Author author3 = new Author(3L,"易",14,"是这个世界在限制他的思维",null);
    7. Author author4 = new Author(3L,"易",14,"是这个世界在限制他的思维",null);
    8. //书籍列表
    9. List<Book> books1 = new ArrayList<>();
    10. List<Book> books2 = new ArrayList<>();
    11. List<Book> books3 = new ArrayList<>();
    12. books1.add(new Book(1L,"刀的两侧是光明与黑暗","哲学,爱情",88,"用一把刀划分了爱恨"));
    13. books1.add(new Book(2L,"一个人不能死在同一把刀下","个人成长,爱情",99,"讲述如何从失败中明悟真理"));
    14. books2.add(new Book(3L,"那风吹不到的地方","哲学",85,"带你用思维去领略世界的尽头"));
    15. books2.add(new Book(3L,"那风吹不到的地方","哲学",85,"带你用思维去领略世界的尽头"));
    16. books2.add(new Book(4L,"吹或不吹","爱情,个人传记",56,"一个哲学家的恋爱观注定很难把他所在的时代理解"));
    17. books3.add(new Book(5L,"你的剑就是我的剑","爱情",56,"无法想象一个武者能对他的伴侣这么的宽容"));
    18. books3.add(new Book(6L,"风与剑","个人传记",100,"两个哲学家灵魂和肉体的碰撞会激起怎么样的火花呢?"));
    19. books3.add(new Book(6L,"风与剑","个人传记",100,"两个哲学家灵魂和肉体的碰撞会激起怎么样的火花呢?"));
    20. author.setBooks(books1);
    21. author2.setBooks(books2);
    22. author3.setBooks(books3);
    23. author4.setBooks(books3);
    24. List<Author> authorList = new ArrayList<>(Arrays.asList(author,author2,author3,author4));
    25. return authorList;
    26. }
    27. }
    28. 复制代码

    假如我们对该作家列表进行操作,要求对作家列表进行去重,并过滤年龄小于18的作家,然后依次打印作者姓名和年龄。

    我们不使用 Stream 流我们可以这样写:

    1. public static void main(String[] args) {
    2. List<Author> authors = getAuthors();
    3. List<Author> fauthors = new ArrayList<>();
    4. //进行去重
    5. for (Author author : authors){
    6. if (!fauthors.contains(author)){
    7. fauthors.add(author);
    8. }
    9. }
    10. authors.clear();
    11. //筛选出年龄小于18
    12. for (Author author : fauthors){
    13. if(author.getAge() < 18){
    14. authors.add(author);
    15. }
    16. }
    17. //输出姓名
    18. for (Author author : authors){
    19. System.out.println(author.getName() + " : " + author.getAge());
    20. }
    21. }
    22. 复制代码

    我们可以发现这种方式非常繁琐,且难懂。

    如果我们使用 stream 流的话,代码就非常简单直观了。

    1. public class StreamDemo {
    2. public static void main(String[] args) {
    3. List<Author> authors = getAuthors();
    4. //把集合转换成流,进行stream流操作
    5. authors.stream()
    6. .distinct() //去重
    7. .filter(author -> author.getAge() < 18)//过滤
    8. .forEach(author -> System.out.println(author.getName())); //打印年龄
    9. }
    10. }
    11. 复制代码

    3. 正式学习之前我们先学习一下Lambda表达式

    Lambda 表达式是 JDK8中的一个语法糖。它可以对某些匿名内部类的写法进行简化。它是函数式编程思想的一个重要体现。让我们不用关注是什么对象,而关注于我们对数据进行了什么操作

    核心原则:可推导可省略

    3.1. 基本格式

    (参数列表)->代码

    例1:

    1. public class Test1 {
    2. public static void main(String[] args) {
    3. new Thread(new Runnable() {
    4. @Override
    5. public void run() {
    6. System.out.println("hi");
    7. }
    8. }).start();
    9. }
    10. }
    11. 复制代码
    1. public class Test1 {
    2. public static void main(String[] args) {
    3. new Thread(()->{
    4. System.out.println("hi");
    5. }).start();
    6. }
    7. }
    8. 复制代码

    例2:

    现有方法定义如下,其中 InitBinaryOperator 是一个接口。先使用匿名内部类的写法调用该方法。

    1. public class Test2 {
    2. public static int calculateNum(IntBinaryOperator operator){
    3. int a = 10;
    4. int b = 10;
    5. return operator.applyAsInt(a,b);
    6. }
    7. public static void main(String[] args) {
    8. int i = calculateNum(new IntBinaryOperator() {
    9. @Override
    10. public int applyAsInt(int left, int right) {
    11. return left + right;
    12. }
    13. });
    14. System.out.println(i);
    15. }
    16. }
    17. 复制代码

    使用 Lambda 表达式的写法:

    1. public class Test2 {
    2. public static void main(String[] args) {
    3. //++++++++++++++lambda表达式写法+++++++++++++++
    4. int i1 = calculateNum((int left, int right) -> {
    5. return left + right;
    6. });
    7. System.out.println(i1);
    8. }
    9. }
    10. 复制代码

    例3:现有方法定义如下,其中 intPredicate 是一个接口。先使用匿名内部类的写法调用该方法。

    1. public class Test3 {
    2. /**
    3. *
    4. * @param predicate IntPredicate接口,实现接口方法 test用于判断数据满足条件
    5. */
    6. public static void printNum(IntPredicate predicate){
    7. int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    8. for(int i: arr){
    9. if(predicate.test(i)){
    10. System.out.println(i);
    11. }
    12. }
    13. }
    14. public static void main(String[] args) {
    15. printNum(new IntPredicate() {
    16. @Override
    17. public boolean test(int value) {
    18. //判断当前参数是否是偶数
    19. if(value%2 == 0) return true;
    20. return false;
    21. }
    22. });
    23. }
    24. }
    25. 复制代码

    使用 Lambda 表达式的写法:

    1. public class Test3 {
    2. public static void main(String[] args) {
    3. System.out.println("+++++++++++++lambda表达式写法++++++++++++++++");
    4. //+++++++++++++lambda表达式写法++++++++++++++++
    5. printNum((int value) ->{
    6. return value%2 == 0;
    7. });
    8. }
    9. }
    10. 复制代码

    例4:现有方法定义如下,其中 Function 是一个接口。先使用匿名内部类的写法调用该方法。

    1. public class Test4 {
    2. public static R typeConver(Function<String, R> function){
    3. String str = "1235";
    4. R result = function.apply(str);
    5. return result;
    6. }
    7. public static void main(String[] args) {
    8. Integer integer = typeConver(new Function<String, Integer>() {
    9. //对字符串进行处理,返回结果
    10. @Override
    11. public Integer apply(String s) {
    12. return s.length();
    13. }
    14. });
    15. System.out.println(integer);
    16. }
    17. }
    18. 复制代码

    使用 Lambda 表达式写法:

    1. public class Test4 {
    2. public static void main(String[] args) {
    3. System.out.println("+++++++++++++lambda表达式写法++++++++++++++++");
    4. Integer integer1 = typeConver((String s) -> {
    5. return s.length();
    6. });
    7. System.out.println(integer1);
    8. }
    9. }
    10. 复制代码

    例5:现有方法定义如下,其中 IntConsumer 是一个接口。先使用匿名内部类的写法调用该方法。

    1. public class Test5 {
    2. public static void foreachArr(IntConsumer consumer){
    3. int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    4. for (int i : arr){
    5. consumer.accept(i);
    6. }
    7. }
    8. public static void main(String[] args) {
    9. foreachArr(new IntConsumer() {
    10. //对数据进行处理
    11. @Override
    12. public void accept(int value) {
    13. System.out.println(value*2);
    14. }
    15. });
    16. }
    17. }
    18. 复制代码

    使用 Lambda 表达式写法:

    1. public class Test5 {
    2. public static void main(String[] args) {
    3. System.out.println("+++++++++++++lambda表达式写法++++++++++++++++");
    4. foreachArr((int value) ->{
    5. System.out.println(value * 2);
    6. });
    7. }
    8. }
    9. 复制代码

    3.2. 省略规则

    1. 参数类型可以省略
    2. 方法体只有一句代码时大括号{}、return以及一行代码后的 ; 号可以省略
    3. 方法只有一个参数时小括号可以省略

    如:

    1. public class Test5 {
    2. public static void main(String[] args) {
    3. foreachArr(new IntConsumer() {
    4. //对数据进行处理
    5. @Override
    6. public void accept(int value) {
    7. System.out.println(value*2);
    8. }
    9. });
    10. System.out.println("+++++++++++++lambda表达式写法++++++++++++++++");
    11. foreachArr((int value) ->{
    12. System.out.println(value * 2);
    13. });
    14. System.out.println("+++++++++++++lambda表达式省略写法++++++++++++++++");
    15. foreachArr(value -> System.out.println(value * 2));
    16. }
    17. }
    18. 复制代码

    4. 常用操作

    4.1. 创建流

    单列集合:集合对象.stream()

    1. List<Author> authors = getAuthors();
    2. Stream<Author> stream = authors.stream();
    3. 复制代码

    数组:Arrays.stream(数组)或者使用 Steam.of(数组)来创建

    1. Integer[] arr = {1, 2, 3, 4, 5};
    2. Stream<Integer> stream = Arrays.stream(arr);
    3. Stream<Integer> stream2 = Steam.of(arr);
    4. 复制代码

    双列集合:转换成单列集合后再创建

    1. Map<String, Integer> map = new HashMap<>();
    2. map.put("1", 19);
    3. map.put("2", 19);
    4. map.put("3", 19);
    5. Stream<Map.Entry<String, Integer>> stream = map.entrySet().stream();
    6. 复制代码

    4.2. 中间操作

    1. filter() 方法,可以对流中的元素进行条件过滤,符合过滤条件的才能继续留在流中。
    1. public static void printAllAuthors(){
    2. List<Author> authors = getAuthors();
    3. authors.stream().filter(author -> author.getName().length() > 1)
    4. .forEach(author -> {
    5. System.out.println(author.getName());
    6. });
    7. }
    8. 复制代码
    1. map() 方法,可以把流中元素进行计算或者转换,使其返回新的值(覆盖原先的值)。相当于一种映射操作。操作之后,返回改变后新的流元素。
    1. public static void test4(){
    2. List<Author> authors = getAuthors();
    3. authors.stream().map(author -> author.getName())
    4. .forEach(name -> {
    5. System.out.println(name);
    6. });
    7. }
    8. 复制代码

    1. distinct() 方法,可以去除流中重复的元素
    1. public static void test5(){
    2. List<Author> authors = getAuthors();
    3. authors.stream()
    4. .distinct()
    5. .map(author -> author.getName())
    6. .forEach(name -> System.out.println(name));
    7. }
    8. 复制代码

    注意:distinct() 方法是依赖 Objectsequals() 方法来判断对象是否相同。自定义对象实体类,注意重写 equals()hashCode() 方法。

    1. sorted 方法,可以对流中的元素进行排序。
    1. public static void test6(){
    2. List<Author> authors = getAuthors();
    3. authors.stream()
    4. .distinct()
    5. .sorted((o1, o2) -> o1.getAge() - o2.getAge())
    6. .forEach(author -> System.out.println(author.getAge()));
    7. }
    8. 复制代码

    sorted() 方法传入一个比较器 Comparator,实现 compare() 方法,传入比较规则。

    1. public static void test6(){
    2. List<Author> authors = getAuthors();
    3. authors.stream()
    4. .distinct()
    5. .sorted(new Comparator<Author>() {
    6. @Override
    7. public int compare(Author o1, Author o2) {
    8. return o1.getAge() - o2.getAge();
    9. }
    10. })
    11. .forEach(author -> System.out.println(author.getAge()));
    12. }
    13. 复制代码
    1. limit() 方法,可以设置流的最大长度,超出的部分将被抛弃。
    1. private static void test7() {
    2. List<Author> authors = getAuthors();
    3. authors.stream()
    4. .distinct()
    5. .sorted((a1, a2) -> a2.getAge() - a1.getAge())
    6. .limit(2)
    7. .forEach(author -> System.out.println(author.getName()));
    8. }
    9. 复制代码

    对这个流分析图有些疑惑,为什么sortedlimit 中间操作的结果一致呢?

    1. skip() 方法,跳过流中的前 n 个元素,返回剩下的元素。
    1. private static void test8() {
    2. List<Author> authors = getAuthors();
    3. authors.stream()
    4. .distinct()
    5. .sorted((a1, a2) -> a2.getAge() - a1.getAge())
    6. .skip(1)
    7. .forEach(a -> System.out.println(a.getName()));
    8. }
    9. 复制代码

    1. flatMap() 方法,map 只能把一个对象转换成另一个对象来作为流中的元素。而 flatMap 可以把一个对象转换为多个对象作为流中的元素。

    我们使用 map 来操作,发现不能进行去重,因为映射出来的是包含书籍列表的流。

    1. private static void test9() {
    2. List<Author> authors = getAuthors();
    3. authors.stream()
    4. .map(author -> author.getBooks())
    5. .forEach(books -> System.out.println(books));
    6. }
    7. 复制代码

    当我们使用 flatMap 进行操作时,会把映射出来的列表中的元素拿出来进行合并作为流对象进行操作。

    1. private static void test9() {
    2. List<Author> authors = getAuthors();
    3. authors.stream()
    4. .flatMap(author -> author.getBooks().stream())
    5. .distinct()
    6. .forEach(book -> System.out.println(book));
    7. }
    8. 复制代码

    4.3. 终结操作

    4.3.1. forEach、count、max/min、collect

    1. forEach() 方法,对流中的元素进行遍历操作,我们通过传入的参数去指定对遍历到的当前院所进行的是什么具体操作。
    1. private static void test10() {
    2. List authors = getAuthors();
    3. authors.stream()
    4. .distinct()
    5. .forEach(author -> System.out.println(author.getName()));
    6. }
    7. 复制代码

    1. count() 方法,可以用来获取当前流中元素的个数。
    1. private static void test11() {
    2. List<Author> authors = getAuthors();
    3. long count = authors.stream()
    4. .flatMap(author -> author.getBooks().stream())
    5. .distinct()
    6. .count();
    7. System.out.println("书籍总数量:" + count);
    8. }
    9. 复制代码

    1. min()max() 方法,可以用来求流中的最值。

    注意:使用 min 或者 max 方法需要传入一个比较器实现具体的排序规则,为什么要这样做呢?因为你操作的流是多个书籍对象,假如你要获取书籍评分最高的书籍对象,那么需要传入具体的比较规则,才能获取到最高评分的数据对象。

    这与我们想象的不同,我们以为是对一组数取最大值,那样就不需要实现比较器。而stream 流为了实现统一,所以需要传入比较器规则。

    minmax 方法相当于经过排序 sortedlimit 限制后的结果。

    注意一旦做出终结操作,流自动关闭,那么该流对象就不能再进行操作了。

    实战

    注意:获取一组对象的最大值和最小值它们的比较规则应是相同的,而不是相反的。

    1. private static void test12() {
    2. List<Author> authors = getAuthors();
    3. Optional<Integer> max = authors.stream()
    4. .flatMap(author -> author.getBooks().stream())
    5. .map(book -> book.getScore())
    6. .max((s1, s2) -> s1 - s2);
    7. System.out.println("最大值:" + max.get());
    8. Optional<Integer> min = authors.stream()
    9. .flatMap(author -> author.getBooks().stream())
    10. .map(book -> book.getScore())
    11. .min((s1, s2) -> s1 - s2);
    12. System.out.println("最小值:" + min.get());
    13. }
    14. 复制代码

    1. collect() 方法,把当前流转换成一个集合,收集。

    collect() 方法需要传入一个参数,指定流转换集合的类型。

    Collectors通过该工具类指定集合的类型

    1. private static void test13() {
    2. List<Author> authors = getAuthors();
    3. List<String> collect = authors.stream()
    4. .distinct()
    5. .map(author -> author.getName())
    6. .collect(Collectors.toList());
    7. System.out.println(collect);
    8. }
    9. 复制代码

    1. private static void test14() {
    2. List<Author> authors = getAuthors();
    3. Set<String> collect = authors.stream()
    4. .flatMap(author -> author.getBooks().stream())
    5. .map(book -> book.getName())
    6. .collect(Collectors.toSet());
    7. System.out.println(collect);
    8. }
    9. 复制代码

    1. private static void test15() {
    2. List<Author> authors = getAuthors();
    3. Map<String, List<Book>> collect = authors.stream()
    4. .distinct()
    5. //分别指定键和值的映射
    6. .collect(Collectors.toMap(author -> author.getName(), author -> author.getBooks()));
    7. System.out.println(collect);
    8. }
    9. 复制代码

    4.3.2. 查找与匹配

    匹配,结果为 boolean 类型

    1. anyMatch() 方法,当流中至少有一个元素符合判断条件,就返回 true

    需要传入一个判断条件,跟 filter方法的过滤条件类似。

    1. private static void test16() {
    2. List<Author> authors = getAuthors();
    3. boolean b = authors.stream()
    4. .distinct()
    5. .anyMatch(author -> author.getAge() > 29);
    6. System.out.println(b ? "存在29岁以上作家" : "不存在");
    7. }
    8. 复制代码

    1. allMatch() 方法,当流中所有元素都满足判断条件,就返回 true
    1. private static void test17() {
    2. List<Author> authors = getAuthors();
    3. boolean b = authors.stream()
    4. .distinct()
    5. .allMatch(author -> author.getAge() > 16);
    6. System.out.println(b ? "作家年龄都大于16岁" : "不匹配");
    7. }
    8. 复制代码

    1. noneMatch() 方法,当流中所有元素都不符合判断条件,返回 true
    1. private static void test18() {
    2. List<Author> authors = getAuthors();
    3. boolean b = authors.stream()
    4. .distinct()
    5. .noneMatch(author -> author.getAge() > 100);
    6. System.out.println(b ? "作家年龄都不大于100岁" : "作家年龄都大于100岁");
    7. }
    8. 复制代码


    查找

    1. findAny() 方法,获取流中任意一个元素,该方法不能保证获取的一定是流中第一个元素。
    1. private static void test19() {
    2. List<Author> authors = getAuthors();
    3. Optional<Author> any = authors.stream()
    4. .distinct()
    5. .filter(author -> author.getAge() > 16)
    6. .findAny();
    7. System.out.println(any.get());
    8. }
    9. 复制代码

    1. findFirst() 方法,获取流中的第一个元素。
    1. private static void test20() {
    2. List<Author> authors = getAuthors();
    3. Optional<Author> first = authors.stream()
    4. .distinct()
    5. .sorted((a1, a2) -> a1.getAge() - a2.getAge())
    6. .findFirst();
    7. first.ifPresent(author -> System.out.println(author.getName()));
    8. }
    9. 复制代码

    4.3.3. reduce归并

    reduce 归并,对流中的数据按照指定的计算方式计算出一个结果(缩减操作)。

    reduce 的作用就是把 stream 流中的元素组合起来,我们可以传入一个初始值,它会按照我们的计算方式依次拿流中的元素和初始值进行计算后返回结果,结果再和后面的元素计算(累加)。

    reduce()方法有三种重载,如下图。

    第一种重载,其内部的计算方式如下:

    1. T result = identity;
    2. for(T element : this.stream){
    3. result = accumulator.apply(result, element);
    4. }
    5. return result;
    6. 复制代码

    其中 identity 就是我们可以通过方法参数传入的初始值, accumulatorapply() 方法,具体进行扫描计算也是通过我们传入的方法参数来确定的。


    第二种重载,其内部的计算方式如下:

    1. boolean foundAny = false;
    2. T result = null;
    3. for (T element : this stream) {
    4. if (!foundAny) {
    5. foundAny = true;
    6. result = element;
    7. }
    8. else
    9. result = accumulator.apply(result, element);
    10. }
    11. return foundAny ? Optional.of(result) : Optional.empty();
    12. 复制代码

    第二种重载方式,由于没有初始值,其内部会在第一次循环时,对 foundAny 进行判断,满足将stream 流中的第一个元素,赋值给初始值,然后进行循环计算。这种方式适用于与自身进行一些运算。


    举例

    1. 使用reduce求所有作者年龄的和
    1. private static void test21() {
    2. List<Author> authors = getAuthors();
    3. Integer reduce = authors.stream()
    4. .map(author -> author.getAge())
    5. .reduce(0, (result, age) -> result + age);
    6. System.out.println(reduce);
    7. }
    8. 复制代码

    这种方式计算所有作者年龄的和,reduce() 方法需要传入两个参数,第一个传入初始值(指定 result 初始值);第二个传入计算规则:result代表结果, age 代表下一个需要累加的值,累加完毕后返回结果给 result ,然后重新累加。

    1. 使用 reduce 求所有作者中年龄的最大值
    1. private static void test22() {
    2. List<Author> authors = getAuthors();
    3. Integer max = authors.stream()
    4. .map(author -> author.getAge())
    5. .reduce(Integer.MIN_VALUE, (result, age) -> result < age ? age : result);
    6. System.out.println(max);
    7. }
    8. 复制代码

    1. 使用 reduce 求所有作者中年龄的最小值
    1. private static void test23() {
    2. List<Author> authors = getAuthors();
    3. Integer min = authors.stream()
    4. .map(author -> author.getAge())
    5. .reduce(Integer.MAX_VALUE, (result, age) -> result > age ? age : result);
    6. System.out.println(min);
    7. }
    8. 复制代码

    1. 通过reduce 第二种重载,求所有作者中年龄的最小值
    1. private static void test24() {
    2. Optional<Integer> minOptional = getAuthors().stream()
    3. .map(author -> author.getAge())
    4. .reduce((result, age) -> result < age ? result : age);
    5. minOptional.ifPresent(min -> System.out.println(min.intValue()));
    6. }
    7. 复制代码

    5. 注意事项

    1. 不要惰性求值(如果没有终结操作,中间操作是不会得到执行的)
    2. 流是一次性的(一旦一个流对象经过一个终结操作后,这个流就不能再被使用)
    3. 不会影响原数据(我们在流中可以对数据做很多处理,不会对原数据有影响)
  • 相关阅读:
    Android:使用命令行发现keytool不是内部命令解决办法
    oa系统是什么?有哪些功能和作用?
    C#通过Process调用Python脚本
    YOLOv5算法改进(11)— 主干网络介绍(MobileNetV3、ShuffleNetV2和GhostNet)
    My Seventy-seventh Page - 零钱兑换 - By Nicolas
    哨兵模式(sentinel)
    Prometheus Operator 通过additional 添加target
    tasklet的实现(原理篇)
    PyTorch-12 GAN、WGAN
    0301yarn&mapredude入门-hadoop-大数据学习
  • 原文地址:https://blog.csdn.net/m0_73311735/article/details/127550602