• 关于:Java8新特性函数式编程 - Lambda、Stream流、Optional


    1.常用方法

    1.1中间操作

    filter

    可以对流中的元素进行条件过滤,符合过滤条件的才能继续留在流中

    例如,打印所有姓名长度大于1的作家的姓名

    List<Author> authors = getAuthors();
    authors.stream().filter(author -> author.getName().length() > 1)
      .forEach(author -> System.out.println(author.getName()));
    
    • 1
    • 2
    • 3

    map

    可以把对流中的元素进行计算或转换

    例如,打印所有作家的姓名

    List<Author> authors = getAuthors();
    authors.stream().map(author -> author.getName())
      .forEach(name->System.out.println(name));
    
    • 1
    • 2
    • 3

    distinct

    去除流中的重复元素

    例如, 打印所有作家的姓名,并且要求其中不能有重复元素。

    List<Author> authors = getAuthors();
    authors.stream().distinct().forEach(author -> System.out.println(author.getName()));
    
    • 1
    • 2

    注意:distinct方法是依赖Object的equals方法来判断是否是相同对象的。所以需要注意重写equals方法。

    import groovy.transform.EqualsAndHashCode;
    import lombok.Data;
    
    import java.util.Objects;
    
    @Data
    @EqualsAndHashCode
    class Author {
        private Long id;
        private String name;
        private Integer age;
        private Integer createTime;
    
        /**
         * 重写此方法
         * @param o
         * @return
         */
        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            Author author = (Author) o;
            return Objects.equals(id, author.id) &&
                    Objects.equals(name, author.name) &&
                    Objects.equals(age, author.age) &&
                    Objects.equals(createTime, author.createTime);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29

    sorted

    对流中的元素进行排序

    例如,对流中的元素按照年龄进行降序排序,并且要求不能有重复的元素。

    List<Author> authors = getAuthors();
    // 1、对流中的元素按照年龄进行降序排序,并且要求不能有重复的元素。
    authors.stream().distinct().sorted().forEach(
      author -> System.out.println(author.getAge())
    );
    List<Author> authors = getAuthors();
    // 2、对流中的元素按照年龄进行降序排序,并且要求不能有重复的元素。
    authors.stream().distinct().sorted((o1, o2) -> o2.getAge() - o1.getAge())
      .forEach(author -> System.out.println(author.getAge()));
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    注意:如果调用空参的sorted()方法(例1中),需要流中的元素实现了Comparable,详情可以看下面Author源码。

    import lombok.Data;
    
    @Data
    class Author implements Comparable<Author> {
        private Long id;
        private String name;
        private Integer age;
        private Integer createTime;
    
      	/**
      	 * 必须实现此方法
      	 */
        @Override
        public int compareTo(Author author) {
            return 0;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    limit

    可以设置流的最大长度,超出的部分将被抛弃。

    例如,对流中的元素按照年龄进行降序排序,并且要求不能有重复的元素,然后打印其中年龄最大的两个作家的姓名。

    List<Author> authors =getAuthors();
    authors.stream().distinct().sorted().limit(2)
      .forEach(author -> System.out.println(author.getName()));
    
    • 1
    • 2
    • 3

    skip

    跳过流中的前n个元素,返回剩下的元素

    例如,打印除了年龄最大的作家外的其他作家,要求不能有重复元素,并且按照年龄降序排序。

    List<Author> authors = getAuthors();authors.stream().distinct().sorted()
      .skip(1).forEach(author -> System.out.println(author.getName()));
    
    • 1
    • 2

    flatMap

    map只能把一个对象转换成另一个对象来作为流中的元素。而flatMap可以把一个对象转换成多个对象作为流中的元素。

    例一:

    打印所有书籍的名字。要求对重复的元素进行去重。
    
    • 1
    List<Author> authors = getAuthors();
    authors.stream().flatMap(author -> author.getBooks().stream())
      .distinct()
      .forEach(book -> System.out.println(book.getName()));
    
    • 1
    • 2
    • 3
    • 4

    例二:

    打印现有数据的所有分类。要求对分类进行去重。不能出现这种格式:哲学,爱情
    
    • 1
    List<Author> authors = getAuthors();authors.stream()
      .flatMap(author -> author.getBooks().stream())
      .distinct()
      .flatMap(book -> Arrays.stream(book.getCategory().split(",")))
      .distinct()
      .forEach(category-> System.out.println(category));
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    1.2终结操作

    forEach

    ​ 对流中的元素进行遍历操作,我们通过传入的参数去指定对遍历到的元素进行什么具体操作。

    例子,输出所有作家的名字:

    List<Author> authors = getAuthors();
    authors.stream().map(author -> author.getName()).distinct()
      .forEach(name-> System.out.println(name));
    
    • 1
    • 2
    • 3

    count

    可以用来获取当前流中元素的个数。

    例子,打印这些作家的所出书籍的数目,注意删除重复元素。

    List<Author> authors = getAuthors();
    long count = authors.stream()
      .flatMap(author -> author.getBooks().stream())
      .distinct().count();
    System.out.println(count);
    
    • 1
    • 2
    • 3
    • 4
    • 5

    min&max

    可以用来或者流中的最值。

    例子,分别获取这些作家的所出书籍的最高分和最低分并打印。

    // 分别获取这些作家的所出书籍的最高分和最低分并打印。
    // Stream -> Stream -> Stream -> 求值List
    <Author> authors = getAuthors();
    Optional<Integer> max = authors.stream()
      .flatMap(author -> author.getBooks().stream())
      .map(book -> book.getScore())
      .max((score1, score2) -> score1 - score2);
    Optional<Integer> min = authors.stream()
      .flatMap(author -> author.getBooks().stream())
      .map(book -> book.getScore())
      .min((score1, score2) -> score1 - score2);
    System.out.println(max.get());
    System.out.println(min.get());
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    collect

    把当前流转换成一个集合。

    例子:

    1、获取一个存放所有作者名字的List集合。
    
    • 1
    List<Author> authors = getAuthors();
    List<String> nameList = authors.stream()
      .map(author -> author.getName())
      .collect(Collectors.toList());
    System.out.println(nameList);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    2、获取一个所有书名的Set集合。
    
    • 1
    List<Author> authors = getAuthors();
    Set<Book> books = authors.stream()
      .flatMap(author -> author.getBooks().stream())
      .collect(Collectors.toSet());
    System.out.println(books);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    3、获取一个Map集合,map的key为作者名,value为List
    
    • 1
    List<Author> authors = getAuthors();
    Map<String, List<Book>> map = authors.stream().distinct()
      .collect(
      	Collectors.toMap(author -> author.getName(), author -> author.getBooks())
    	);
    System.out.println(map);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    1.3查找与匹配

    anyMatch

    可以用来判断是否有任意符合匹配条件的元素,结果为boolean类型。

    例子,判断是否有年龄在29以上的作家

    List<Author> authors = getAuthors();
    boolean flag = authors.stream()
      .anyMatch(author -> author.getAge() > 29);
    System.out.println(flag);
    
    • 1
    • 2
    • 3
    • 4

    allMatch

    可以用来判断是否都符合匹配条件,结果为boolean类型。如果都符合结果为true,否则结果为false。

    例子,判断是否所有的作家都是成年人

    List<Author> authors = getAuthors();
    boolean flag = authors.stream()
      .allMatch(author -> author.getAge() >= 18);
    System.out.println(flag);
    
    • 1
    • 2
    • 3
    • 4

    noneMatch

    可以判断流中的元素是否都不符合匹配条件。如果都不符合结果为true,否则结果为false。

    例子,判断作家是否都没有超过100岁的。

    List<Author> authors = getAuthors();
    boolean b = authors.stream().noneMatch(author -> author.getAge() > 100);
    System.out.println(b);
    
    • 1
    • 2
    • 3

    findAny

    获取流中的任意一个元素。该方法没有办法保证获取的一定是流中的第一个元素。

    例子,获取任意一个年龄大于18的作家,如果存在就输出他的名字

    List<Author> authors = getAuthors();
    Optional<Author> optionalAuthor = authors.stream()
      .filter(author -> author.getAge()>18).findAny();
    optionalAuthor.ifPresent(author -> System.out.println(author.getName()));
    
    • 1
    • 2
    • 3
    • 4

    findFirst

    获取流中的第一个元素。

    例子,获取一个年龄最小的作家,并输出他的姓名。

    List<Author> authors = getAuthors();
    Optional<Author> first = authors.stream()
      .sorted((o1, o2) -> o1.getAge() - o2.getAge()).findFirst();
    first.ifPresent(author -> System.out.println(author.getName()));
    
    • 1
    • 2
    • 3
    • 4

    reduce

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

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

    reduce两个参数的重载形式内部的计算方式如下:

    T result = identity;
    for (T element : this stream)result = accumulator.apply(result, element)
    return result;
    
    • 1
    • 2
    • 3

    其中identity就是我们可以通过方法参数传入的初始值,accumulator的apply具体进行什么计算也是我们通过方法参数来确定的。

    例子,使用reduce求所有作者年龄的和

    List<Author> authors = getAuthors();
    Integer sum = authors.stream().distinct()
    	.map(author -> author.getAge())
      .reduce(0, (result, element) -> result + element);
    System.out.println(sum);
    
    • 1
    • 2
    • 3
    • 4
    • 5

    使用reduce求所有作者中年龄的最大值

    List<Author> authors = getAuthors();
    Integer max = authors.stream().map(author -> author.getAge())
      .reduce(Integer.MIN_VALUE, (result, element) -> result < element ? element : result);
    System.out.println(max);
    
    • 1
    • 2
    • 3
    • 4

    使用reduce求所有作者中年龄的最小值

    List<Author> authors = getAuthors();
    Integer min = authors.stream().map(author -> author.getAge())
      .reduce(Integer.MAX_VALUE, (result, element) -> result > element ? element : result);
    System.out.println(min);
    
    • 1
    • 2
    • 3
    • 4

    reduce一个参数的重载形式内部的计算

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

    如果用一个参数的重载方法去求最小值代码如下:

    List<Author> authors = getAuthors();
    Optional<Integer> minOptional = authors.stream()
      .map(author -> author.getAge())
      .reduce((result, element) -> result > element ? element : result);
    minOptional.ifPresent(age-> System.out.println(age));
    
    • 1
    • 2
    • 3
    • 4
    • 5

    2.lambda表达式

    2.1 概述

    • lambda是JDK8中的一个语法糖,可
      以对某些匿名内部类的写法进行优化,让函数式编程只关注数据而不是对象。
    • 基本格式:(参数列表)->{代码}

    2.2 学习目的

    • 代码可读性
    • 避免过分嵌套
    • 看懂别人写的代码
    • 大数据量下集合处理效率
    • 底层使用多线程处理并线程安全可以保障?

    2.3 函数式编程思想

    • 面向对象思想主要是关注对象能完成什么事情,函数式编程思想就像函数式,主要是针对数据操作;
    • 代码简洁容易理解,方便于并发编程,不需要过分关注线程安全问题

    3. stream流

    3.1 概述

    • stream使用的是函数式编程模式,可以被用来对集合或数组进行链状流式的操作
    • 有别于其他输入输出流,这里是针对集合操作数据的流哦
    • 创建流实战:com.yjiewei.TestStream

    3.2 功能

    • 流不存储元素。它只是通过计算操作的流水线从数据结构, 数组或I/O通道等源中传递元素。
    • 流本质上是功能性的。对流执行的操作不会修改其源。例如, 对从集合中获取的流进行过滤会产生一个新的不带过滤元素的流, 而不是从源集合中删除元素。
    • Stream是惰性的, 仅在需要时才评估代码。
    • 在流的生存期内, 流的元素只能访问一次。像Iterator一样, 必须生成新的流以重新访问源中的相同元素。

    3.3 参考资料

    • https://www.xjx100.cn/news/258852.html?action=onClick
    • https://www.bookstack.cn/read/liaoxuefeng-java/e8328b3bd5d8f00f.md

    3.4 注意事项

    • 惰性求值,如果没有终结操作是不会执行的
    • 流是一次性的,经过终结操作之后就不能再被使用
    • 不会影响元数据

    4.Optional

    4.1 概述

    很多情况下代码容易出现空指针异常,尤其对象的属性是另外一个对象的时候,
    判断十分麻烦,代码也会很臃肿,这种情况下Java 8 引入了optional来避免空指针异常,
    并且很多函数式编程也会用到API也都用到

    4.2 使用

    1. 创建对象
    • optional就像是包装类,可以把我们的具体数据封装Optional对象内部,
      然后我们去使用它内部封装好的方法操作封装进去的数据就可以很好的避免空指针异常
    • 一般我们使用Optional.ofNullable来把数据封装成一个optional对象,无论传入的参数是否为null都不会出现问题
      Author author = getAuthor(); Optional author = Optional.ofNullable(author);
    • 如果你确定一个对象不是空的话就可以用Optional.of这个静态方法来把数据封装成Optional对象
      Optional.of(author);这里一定不能是null值传入,可以试试会出现空指针
    • 如果返回的是null,这时可以使用Optional.empty()来进行封装
    1. 安全消费值
    • 当我们获取到一个Optional对象的时候,可以用ifPresent方法来去消费其中的值,
      这个方法会先去判断是否为空,不为空才会去执行消费代码,优雅避免空指针
      OptionalObject.ifPresent()
    1. 获取值
    • Optional.get() 这种方法不推荐,当Optional的get方法为空时会出现异常

    3.1 安全获取值

    • orElseGet:获取数据并且设置数据为空时的默认值,如果数据不为空就获取该数据,为空则获取默认值
    • orElseThrow
    1. 过滤
    • 我们可以使用filter方法对数据进行过滤,如果原来是有数据的,但是不符合判断,也会变成一个无数据的Optional对象
    • Optional.filter()
    1. 判断
    • Optional.isPresent() 判断数据是否存在,空则返回false,否则true,这种方式不是最好的,推荐使用Optional.ifPresent()
    • Optional.ifPresent(),上面isPresent不能体现Optional的优点
    • 使用的时候可以先判断,相当于先判空,再去get,这样就不会空指针了
    1. 数据转换
    • Optional还提供map可以对数据进行转换,并且转换得到的数据还是Optional包装好的,保证安全使用

    5.函数式接口

    5.1 概述

    1. 只有一个抽象方法的接口就是函数式接口
    2. JDK的函数式接口都加上了@FunctionalInterface注解进行标识,但是无论加不加该注解,只要接口中只有一个抽象方法,都是函数式接口
    3. 常见的函数式接口
    • Consumer 消费接口:可以对传入的参数进行消费
    • Function 计算转换接口:根据其中抽象方法的参数列表和返回值类型可以看到,可以在方法中对传入的参数计算或转换,把结果返回
    • Predicate 判断接口:可以在方法对传入的参数条件进行判断,返回判断结果
    • Supplier 生产型接口:可以在方法中创建对象,把创建好的对象返回
    1. 常用的默认方法
    • and :我们在使用Predicate接口的时候可能需要进行判断条件的拼接,而and方法相当于使用&&来拼接两个判断条件
    • or

    6.方法引用

    • 我们在使用lambda时,如果方法体中只有一个方法的时候,包括构造方法,我们可以用方法引用进一步简化代码

    6.1用法及基本格式

    6.2语法了解

    • 6.2.1 引用类静态方法 类名::方法名
      使用前提:如果我们在重写方法的时候,方法体中只有一行代码,
      并且这行代码是调用了某个类的静态方法,并且我们把要重写的抽象方法中所有参数都按照顺序传入了这个静态方法中,
      这个时候我们就可以引用类的静态方法。

    • 6.2.2 引用对象的实例方法 对象名::方法名
      使用前提:如果我们在重写方法的时候,方法体只有一行代码,并且这行代码是调用了某个对象的成员方法,
      并且我们把要重写的抽象方法里面中所有的参数都按照顺序传入了这个成员方法(就是类的方法)中,这个时候我们就可以引用对象的实例方法。

    • 6.2.3 引用类的实例方法 类名::方法名
      使用前提:如果我们在重写方法的时候,方法体中只有一行代码,并且这行代码是调用了第一个参数的成员方法,
      并且我们把要重写的抽象方法中剩余的所有的参数都按照顺序传入了这个成员方法中,这个时候我们就可以引用类的实例方法。

    • 6.2.4 构造器引用 类名::new StringBuilder::new

    7.高级用法

    基本数据类型优化:很多stream方法由于都使用了泛型,所以涉及到的参数和返回值都是引用数据类型,即使我们操作的是
    整数小数,实际使用还是他们的包装类,JDK5中引入的自动装箱和自动拆箱让我们在使用对应的包装类时就好像使用基本数据类型一样方便,
    但是你一定要知道装箱拆箱也是需要一定的时间的,虽然这个时间消耗很小,但是在大量数据的不断重复的情况下,就不能忽视这个时间损耗了,
    stream对这块内容进行了优化,提供很多针对基本数据类型的方法。
    例如:mapToInt,mapToLong,mapToDouble,flatMapToInt…
    比如前面我们用的map(),返回的是Stream,如果你用.mapToInt(),最后返回的就是int值

    8.并行流

    当流中有大量元素时,我们可以使用并行流去提高操作的效率,其实并行流就是把任务分配给多个线程去完成,如果我们自己去用代码取实现的话
    其实会非常复杂,并且要求你对并发编程有足够的理解和认识,而且如果我们使用stream的话,我们只需要修改一个方法的调用就可以使用并行流来帮我们实现,从而提高效率

  • 相关阅读:
    Python Number degrees()实例讲解
    浅谈测试需求分析
    《昇思25天学习打卡营第17天|K近邻算法实现红酒聚类》
    Jackson ObjectNode JsonNode --> FastJson JSONObject
    智慧工地技术方案
    后端java部署教程,docker配置解读(linux用docker部署新手入门)
    2023最新SSM计算机毕业设计选题大全(附源码+LW)之java高校学生社团管理系统n4pcu
    Windows安装Docker Desktop并配置镜像、修改内存占用大小
    线上问题:多实例引发的Read timed out 服务器出错
    灰色预测模型
  • 原文地址:https://blog.csdn.net/wpj130/article/details/133394828