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

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

函数式编程 stream流

1.常用方法

1.1中间操作
filter

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

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

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

map

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

例如打印所有作家的姓名

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

distinct

去除流中的重复元素

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

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

注意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);
    }
}

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()));

注意如果调用空参的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;
    }
}

limit

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

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

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

skip

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

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

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

flatMap

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

例一

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

例二

打印现有数据的所有分类。要求对分类进行去重。不能出现这种格式哲学,爱情
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终结操作
forEach

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

例子输出所有作家的名字

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

count

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

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

List<Author> authors = getAuthors();
long count = authors.stream()
  .flatMap(author -> author.getBooks().stream())
  .distinct().count();
System.out.println(count);

min&max

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

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

// 分别获取这些作家的所出书籍的最高分和最低分并打印。
// Stream<Author> -> Stream<Book> -> Stream<Integer> -> 求值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());

collect

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

例子

1、获取一个存放所有作者名字的List集合。
List<Author> authors = getAuthors();
List<String> nameList = authors.stream()
  .map(author -> author.getName())
  .collect(Collectors.toList());
System.out.println(nameList);
2、获取一个所有书名的Set集合。
List<Author> authors = getAuthors();
Set<Book> books = authors.stream()
  .flatMap(author -> author.getBooks().stream())
  .collect(Collectors.toSet());
System.out.println(books);
3、获取一个Map集合map的key为作者名value为List
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.3查找与匹配
anyMatch

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

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

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

allMatch

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

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

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

noneMatch

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

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

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

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()));

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()));

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

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

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

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

其中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);

使用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);

使用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);

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();

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

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));

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> 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的话我们只需要修改一个方法的调用就可以使用并行流来帮我们实现从而提高效率

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6
标签: Java