1. 函数式编程

函数式编程近几年炒的火热,其实函数式编程其实很早就有了,支持该范式的语言有大名鼎鼎的C、JavaScript、PHP等,那为什么又进行了一波高潮呢,我们来探究一下。首先了解一下什么是函数式编程:

函数式编程(英语:functional programming)或称函数程序设计、泛函编程,是一种编程范式,它将电脑运算视为函数运算,并且避免使用程序状态以及易变对象。其中,λ演算为该语言最重要的基础。而且,λ演算的函数可以接受函数作为输入参数和输出返回值。
——维基百科

简而言之,函数式是一种编程范式,同时函数式也是一种以函数为核心的编程思维方式。面向对象思想需要关注用什么对象完成什么事情,而函数式编程思想就类似于我们数学中的函数,它主要关注的是对数据进行了什么操作。

函数式编程的优点

  • 代码简洁,开发快速
  • 接近自然语言,易于理解
  • 易于并发编程

为什么学函数式编程

  • 能够看懂公司里的代码
  • 大数量下处理集合效率高
  • 代码可读性高
  • 消灭嵌套地狱

请看下面一段代码,查询未成年作家的评分在70以上的书籍,作家和书籍可能出现重复,需要进行去重。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
List<Book> bookList = new ArrayList<>();
Set<Book> uniqueBookValues = new HashSet<>();
Set<Author> uniqueAuthorValues = new HashSet<>();
for (Author author : authors) {
if (uniqueAuthorValues.add(author)) {
if (author.getAge() < 18) {
List<Book> books = author.getBooks();
for (Book book : books) {
if (book.getScore() > 70) {
if (uniqueBookValues.add(book)) {
bookList.add(book);
}
}
}
}
}
}
System.out.println(bookList);

如果使用函数式编程的写法,代码更加简洁,可读性高

1
2
3
4
5
6
7
8
9
List<Book> collect = authors.stream()
.distinct()
.filter(author -> author.getAge() < 18)
.map(author -> author.getBooks())
.flatMap(Collection::stream)
.filter(book -> book.getScore() > 70)
.distinct()
.collect(Collectors.toList());
System.out.println(collect);

2.Lambda表达式

Java 函数式编程的核心是 Lambda 表达式,它们是 Java 函数式编程的推动者。事实上,当我们提到函数式编程时,本质上就是Lambda 表达式。Lambda表达式是JDK8中一个语法糖。他可以对某些匿名内部类的写法进行简化。它是函数式编程思想的一个重要体现。让我们不用关注是什么对象。而是更关注我们对数据进行了什么操作。

基本格式:(参数列表)->{代码}

例一:我们在创建线程并启动时可以使用匿名内部类的写法:

1
2
3
4
5
6
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("你知道吗 我比你想象的 更想在你身边");
}
}).start();

可以使用Lambda的格式对其进行修改。修改后如下:

1
2
3
new Thread(()->{
System.out.println("你知道吗 我比你想象的 更想在你身边");
}).start();

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public static int calculateNum(IntBinaryOperator operator){
int a = 10;
int b = 20;
return operator.applyAsInt(a, b);
}

public static void main(String[] args) {
int i = calculateNum(new IntBinaryOperator() {
@Override
public int applyAsInt(int left, int right) {
return left + right;
}
});
System.out.println(i);
}

Lambda写法:

1
2
3
4
5
6
public static void main(String[] args) {
int i = calculateNum((int left, int right)->{
return left + right;
});
System.out.println(i);
}

Lambda表达式省略规则

  • 参数类型可以省略
  • 方法体只有一句代码时大括号return和唯一一句代码的分号可以省略
  • 方法只有一个参数时小括号可以省略
  • 以上这些规则都记不住也可以省略不记

3. Stream流

Java8的Stream使用的是函数式编程模式,如同它的名字一样,它可以被用来对集合或数组进行链状流式的操作。可以更方便的让我们对集合或数组操作。

数据准备

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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
@Data
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode
public class Author {
//id
private Long id;
//姓名
private String name;
//年龄
private Integer age;
//简介
private String intro;
//作品
private List<Book> books;
}
@Data
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode
public class Book {
// id
private Long id;
// 书名
private String name;
// 分类
private String category;
// 评分
private Integer score;
// 简介
private String intro;
}
private static List<Author> getAuthors() {
//数据初始化
Author author1 = new Author(1L, "蒙多", 33, "一个从菜刀中明悟哲理的祖安人", null);
Author author2 = new Author(2L, "亚拉索", 15, "狂风也追逐不上他的思考速度", null);
Author author3 = new Author(3L, "易", 14, "是这个世界在限制他的思维", null);
Author author4 = new Author(3L, "易", 14, "是这个世界在限制他的思维", null);

//书籍列表
List<Book> books1 = new ArrayList<>();
List<Book> books2 = new ArrayList<>();
List<Book> books3 = new ArrayList<>();

books1.add(new Book(1L, "刀的两侧是光明与黑暗", "哲学,爱情", 88, "用一把刀划分了爱恨"));
books1.add(new Book(2L, "一个人不能死在同一把刀下", "个人成长,爱情", 99, "讲述如何从失败中明悟真理"));

books2.add(new Book(3L, "那风吹不到的地方", "哲学", 85, "带你用思维去领略世界的尽头"));
books2.add(new Book(3L, "那风吹不到的地方", "哲学", 85, "带你用思维去领略世界的尽头"));
books2.add(new Book(4L, "吹或不吹", "爱情,个人传记", 56, "一个哲学家的恋爱观注定很难把他所在的时代理解"));

books3.add(new Book(5L, "你的剑就是我的剑", "爱情", 56, "无法想象一个武者能对他的伴侣这么的宽容"));
books3.add(new Book(6L, "风与剑", "个人传记", 100, "两个哲学家灵魂和肉体的碰撞会激起怎么样的火花呢?"));
books3.add(new Book(6L, "风与剑", "个人传记", 100, "两个哲学家灵魂和肉体的碰撞会激起怎么样的火花呢?"));

author1.setBooks(books1);
author2.setBooks(books2);
author3.setBooks(books3);
author4.setBooks(books3);

return new ArrayList<>(Arrays.asList(author1, author2, author3, author4));
}

我们可以调用getAuthors方法获取到作家的集合。现在需要打印所有年龄小于18的作家的名字,并且要注意去重。

1
2
3
4
5
6
// 打印所有年龄小于18的作家的名字,并且要注意去重
List<Author> authors = getAuthors();
authors.stream()//把集合转换成流
.distinct()//先去除重复的作家
.filter(author -> author.getAge()<18)//筛选年龄小于18的
.forEach(author -> System.out.println(author.getName()));//遍历打印名字

常用操作

创建流

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

1
2
List<Author> authors = getAuthors();
Stream<Author> stream = authors.stream();

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

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

中间操作

filter

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

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

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

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

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

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

可以去除流中的重复元素。

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

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

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

sorted

可以对流中的元素进行排序。

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

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

注意:如果调用空参的sorted()方法,需要流中的元素是实现了Comparable。

limit

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

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

1
2
3
4
5
6
7
// 对流中的元素按照年龄进行降序排序,并且要求不能有重复的元素,然后打印其中年龄最大的两个作家的姓名。
List<Author> authors = getAuthors();
authors.stream()
.distinct()
.sorted()
.limit(2)
.forEach(author -> System.out.println(author.getName()));
skip

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

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

1
2
3
4
5
6
7
// 打印除了年龄最大的作家外的其他作家,要求不能有重复元素,并且按照年龄降序排序。
List<Author> authors = getAuthors();
authors.stream()
.distinct()
.sorted()
.skip(1)
.forEach(author -> System.out.println(author.getName()));
flatMap

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

例一:打印所有书籍的名字。要求对重复的元素进行去重。

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

例二:打印现有数据的所有分类。要求对分类进行去重。不能出现这种格式:哲学,爱情

1
2
3
4
5
6
7
8
// 打印现有数据的所有分类。要求对分类进行去重。不能出现这种格式:哲学,爱情 爱情
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));

终结操作

forEach

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

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

1
2
3
4
5
6
// 输出所有作家的名字
List<Author> authors = getAuthors();
authors.stream()
.map(author -> author.getName())
.distinct()
.forEach(name-> System.out.println(name));
count

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

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

1
2
3
4
5
6
7
// 打印这些作家的所出书籍的数目,注意删除重复元素。
List<Author> authors = getAuthors();
long count = authors.stream()
.flatMap(author -> author.getBooks().stream())
.distinct()
.count();
System.out.println(count);
max&min

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 分别获取这些作家的所出书籍的最高分和最低分并打印。
// 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

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

例子:获取一个存放所有作者名字的List集合。

1
2
3
4
5
6
// 获取一个存放所有作者名字的List集合。
List<Author> authors = getAuthors();
List<String> nameList = authors.stream()
.map(author -> author.getName())
.collect(Collectors.toList());
System.out.println(nameList);

获取一个所有书名的Set集合。

1
2
3
4
5
6
7
// 获取一个所有书名的Set集合。
List<Author> authors = getAuthors();
Set<Book> books = authors.stream()
.flatMap(author -> author.getBooks().stream())
.collect(Collectors.toSet());

System.out.println(books);

获取一个Map集合,map的key为作者名,value为List

1
2
3
4
5
6
7
// 获取一个Map集合,map的key为作者名,value为List<Book>
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);
查找与匹配

anyMatch

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

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

1
2
3
4
5
// 判断是否有年龄在29以上的作家
List<Author> authors = getAuthors();
boolean flag = authors.stream()
.anyMatch(author -> author.getAge() > 29);
System.out.println(flag);

allMatch

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

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

1
2
3
4
5
// 判断是否所有的作家都是成年人
List<Author> authors = getAuthors();
boolean flag = authors.stream()
.allMatch(author -> author.getAge() >= 18);
System.out.println(flag);

noneMatch

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

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

1
2
3
4
5
// 判断作家是否都没有超过100岁的。
List<Author> authors = getAuthors();
boolean b = authors.stream()
.noneMatch(author -> author.getAge() > 100);
System.out.println(b);

findAny

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

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

1
2
3
4
5
6
7
// 获取任意一个年龄大于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

获取流中的第一个元素。

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

1
2
3
4
5
6
7
// 获取一个年龄最小的作家,并输出他的姓名。
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两个参数的重载形式内部的计算方式如下:

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

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

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

1
2
3
4
5
6
7
// 使用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求所有作者中年龄的最大值

1
2
3
4
5
6
7
// 使用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求所有作者中年龄的最小值

1
2
3
4
5
6
// 使用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一个参数的重载形式内部的计算

1
2
3
4
5
6
7
8
9
10
11
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
// 使用reduce求所有作者中年龄的最小值
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));

高级用法

基本数据类型优化

我们之前用到的很多Stream的方法由于都使用了泛型。所以涉及到的参数和返回值都是引用数据类型。

即使我们操作的是整数小数,但是实际用的都是他们的包装类。JDK5中引入的自动装箱和自动拆箱让我们在使用对应的包装类时就好像使用基本数据类型一样方便。但是你一定要知道装箱和拆箱肯定是要消耗时间的。虽然这个时间消耗很下。但是在大量的数据不断的重复装箱拆箱的时候,你就不能无视这个时间损耗了。

所以为了让我们能够对这部分的时间消耗进行优化。Stream还提供了很多专门针对基本数据类型的方法。

例如:mapToInt,mapToLong,mapToDouble,flatMapToInt,flatMapToDouble等。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
List<Author> authors = getAuthors();
authors.stream()
.map(author -> author.getAge())
.map(age -> age + 10)
.filter(age->age>18)
.map(age->age+2)
.forEach(System.out::println);

authors.stream()
.mapToInt(author -> author.getAge())
.map(age -> age + 10)
.filter(age->age>18)
.map(age->age+2)
.forEach(System.out::println);

并行流

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

parallel方法可以把串行流转换成并行流。

1
2
3
4
5
6
7
8
9
10
11
12
Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
Integer sum = stream.parallel()
.peek(new Consumer<Integer>() {
@Override
public void accept(Integer num) {
System.out.println(num+Thread.currentThread().getName());
}
})
.filter(num -> num > 5)
.reduce((result, ele) -> result + ele)
.get();
System.out.println(sum);

也可以通过parallelStream直接获取并行流对象。

1
2
3
4
5
6
7
List<Author> authors = getAuthors();
authors.parallelStream()
.map(author -> author.getAge())
.map(age -> age + 10)
.filter(age->age>18)
.map(age->age+2)
.forEach(System.out::println);

注意事项

  • 惰性求值(如果没有终结操作,没有中间操作是不会得到执行的)
  • 流是一次性的(一旦一个流对象经过一个终结操作后,这个流就不能再被使用)
  • 不会影响原数据(我们在流中可以多数据做很多处理,但是正常情况下是不会影响原来集合中的元素的,这往往也是我们期望的)

4. Optional

概述

我们在编写代码的时候出现最多的就是空指针异常。所以在很多情况下我们需要做各种非空的判断。

例如:

1
2
3
4
Author author = getAuthor();
if(author != null){
System.out.println(author.getName());
}

尤其是对象中的属性还是一个对象的情况下。这种判断会更多。而过多的判断语句会让我们的代码显得臃肿不堪。所以在JDK8中引入了Optional,养成使用Optional的习惯后你可以写出更优雅的代码来避免空指针异常。并且在很多函数式编程相关的API中也都用到了Optional,如果不会使用Optional也会对函数式编程的学习造成影响。

使用

创建对象

Optional就好像是包装类,可以把我们的具体数据封装Optional对象内部。然后我们去使用Optional中封装好的方法操作封装进去的数据就可以非常优雅的避免空指针异常。

我们一般使用Optional静态方法ofNullable来把数据封装成一个Optional对象。无论传入的参数是否为null都不会出现问题。

1
2
Author author = getAuthor();
Optional<Author> authorOptional = Optional.ofNullable(author);

你可能会觉得还要加一行代码来封装数据比较麻烦。但是如果改造下getAuthor方法,让其的返回值就是封装好的Optional的话,我们在使用时就会方便很多。

而且在实际开发中我们的数据很多是从数据库获取的。Mybatis从3.5版本可以也已经支持Optional了。我们可以直接把dao方法的返回值类型定义成Optional类型,MyBastis会自己把数据封装成Optional对象返回。封装的过程也不需要我们自己操作。

如果你确定一个对象不是空的则可以使用Optional静态方法of来把数据封装成Optional对象。

1
2
Author author = new Author();
Optional<Author> authorOptional = Optional.of(author);

但是一定要注意,如果使用of的时候传入的参数必须不为null。

如果一个方法的返回值类型是Optional类型。而如果我们经判断发现某次计算得到的返回值为null,这个时候就需要把null封装成Optional对象返回。这时则可以使用Optional静态方法empty来进行封装。

1
Optional.empty()

安全消费值

我们获取到一个Optional对象后肯定需要对其中的数据进行使用。这时候我们可以使用其ifPresent方法对来消费其中的值。

这个方法会判断其内封装的数据是否为空,不为空时才会执行具体的消费代码。这样使用起来就更加安全了。例如,以下写法就优雅的避免了空指针异常。

1
2
Optional<Author> authorOptional = Optional.ofNullable(getAuthor());
authorOptional.ifPresent(author -> System.out.println(author.getName()));

安全获取值

如果我们想获取值自己进行处理可以使用get方法获取,但是不推荐,因为当Optional内部的数据为空的时候会出现异常。如果我们期望安全的获取值,我们不推荐使用get方法,而是使用Optional提供的以下方法。

  • orElseGet

获取数据并且设置数据为空时的默认值。如果数据不为空就能获取到该数据。如果为空则根据你传入的参数来创建对象作为默认值返回。

1
2
Optional<Author> authorOptional = Optional.ofNullable(getAuthor());
Author author1 = authorOptional.orElseGet(() -> new Author());
  • orElseThrow

获取数据,如果数据不为空就能获取到该数据。如果为空则根据你传入的参数来创建异常抛出。

1
2
3
4
5
6
7
Optional<Author> authorOptional = Optional.ofNullable(getAuthor());
try {
Author author = authorOptional.orElseThrow((Supplier<Throwable>) () -> new RuntimeException("author为空"));
System.out.println(author.getName());
} catch (Throwable throwable) {
throwable.printStackTrace();
}

过滤

我们可以使用filter方法对数据进行过滤。如果原本是有数据的,但是不符合判断,也会变成一个无数据的Optional对象。

1
2
Optional<Author> authorOptional = Optional.ofNullable(getAuthor());
authorOptional.filter(author -> author.getAge()>100).ifPresent(author -> System.out.println(author.getName()));

判断

我们可以使用isPresent方法进行是否存在数据的判断。如果为空返回值为false,如果不为空,返回值为true。但是这种方式并不能体现Optional的好处,更推荐使用ifPresent方法

1
2
3
4
5
Optional<Author> authorOptional = Optional.ofNullable(getAuthor());

if (authorOptional.isPresent()) {
System.out.println(authorOptional.get().getName());
}

数据转换

Optional还提供了map可以让我们的对数据进行转换,并且转换得到的数据也还是被Optional包装好的,保证了我们的使用安全。

例如我们想获取作家的书籍集合。

1
2
3
4
5
private static void testMap() {
Optional<Author> authorOptional = getAuthorOptional();
Optional<List<Book>> optionalBooks = authorOptional.map(author -> author.getBooks());
optionalBooks.ifPresent(books -> System.out.println(books));
}

5. 函数式接口

只有一个抽象方法的接口我们称之为函数接口。JDK的函数式接口都加上了@FunctionalInterface 注解进行标识。但是无论是否加上该注解只要接口中只有一个抽象方法,都是函数式接口。

函数式接口的关键特点是可以被Lambda表达式所实现。函数式接口与Lambda表达式结合使用,可以实现更简洁和可读性强的代码。

jdk自带的一些常用的一些接口Callable、Runnable、Comparator等在JDK8中都添加了@FunctionalInterface注解。自定义函数式接口时,@FunctionalInterface是可选的,就算不写这个注解,只要保证满足函数式接口定义的条件,也照样是函数式接口 。

使用函数式接口

示例一

这里我们先定义一个带有一个方法的接口

1
2
3
4
@FunctionalInterface
public interface MyFunctionInterface {
void show();
}

定义一个方法以函数式接口作参数,可以使用多种方法传递。

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
public class UserFunctionInterface {
// 定义一个方法以函数式接口作参数
public static void test(MyFunctionInterface myfun){
myfun.show();
}

public static void main(String[] args) {
// 1.使用匿名内部类的方式
MyFunctionInterface myfun = new MyFunctionInterface() {
@Override
public void show() {
System.out.println("使用匿名内部类的方式实现函数式接口....");
}
};

test(myfun);

// 2.直接传递匿名内部类
test(new MyFunctionInterface() {
@Override
public void show() {
System.out.println("使用直接传递匿名内部类的方式....");
}
});

// 3.使用Lambda表达式的方式使用函数式接口
test(()-> System.out.println("使用Lambda表达式的方式使用函数式接口..."));
}
}

示例二

1
2
3
4
5
6
7
8
9
@FunctionalInterface
interface MyFunction<T, R> {

R apply(T t);
// 默认方法
default <V> MyFunction<T, V> andThen(MyFunction<R, V> after) {
return (T t) -> after.apply(this.apply(t));
}
}

在这个示例中,MyFunction是一个自定义函数式接口,包含一个抽象方法apply,以及一个默认方法andThen,用于组合函数。

常用函数式接口

Java8中提供了一些常用的函数式接口,它们位于java.util.function包中。这些接口涵盖了各种常见的函数操作,包括函数应用、谓词操作、函数组合等。在使用类似功能的时候,不需要额外定义接口,直接使用jdk8中提供的即可。

函数式接口类型参数类型用途
Consumer<T>消费型接口T对类型为T的对象应用操作,包含方法: void accept(T t)
Supplier<T> 供给型接口返回类型为T的对象,包含方法:T get()
Function<T, R>功能型接口T对类型为T的对象应用操作,并返回结果。结果是R类型的对象。包含方法:R apply(T t)
Predicate<T>判断型接口T确定类型为T的对象是否满足某约束,并返回 boolean 值。包含方法:boolean test(T t)

更多其他类型的函数式接口如下图所示:

Supplier接口

java.util.function.Supplier接口仅包含一个无参的方法:T get() 用来获取一个泛型参数指定类型的对象数据。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import java.util.function.Supplier;

/**
* 常用函数式接口
* java.util.function.Supplier<T>接口仅包含一个无参构造方法get()
* Supplier<T>接口称之为生产型接口,指定接口的泛型是什么类型,那么接口中的get方法就会生产什么类型的数据
*/

public class SupplierDemo {
public static Author getAuthor(Supplier<Author> supplier) {
return supplier.get();
}

public static void main(String[] args) {
Author author = getAuthor(() -> new Author(1L, "蒙多", 33, "一个从菜刀中明悟哲理的祖安人", null));
System.out.println(author);
}
}

Consumer接口

java.util.function.Consumer接口则正好与supplier接口相反,他不是产生一个数据,而是消费一个数据,其数据类型由泛型决定。

抽象方法:accept

Consumer接口中包含抽象方法 void accept(T t),意为消费一个指定泛型的数据。

Consumer接口是一个消费型接口,泛型执行什么类型,就可以使用accept方法消费什么类型的数据。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import java.util.function.Consumer;
public class ConsumerDemo {
/*
* 定义一个方法:
* 方法的参数传递Consumer接口,Author
* 可以使用Consumer接口消费Author对象
*/
public static void consumerAuthor(Author author, Consumer<Author> con) {
con.accept(author);
}

public static void main(String[] args) {
Supplier<Author> supplier = () -> new Author(1L, "蒙多", 33, "一个从菜刀中明悟哲理的祖安人", null);
consumerAuthor(supplier.get(), (Author author) -> {
System.out.println(author.getName());
});
}
}
默认方法:andThen

如果一个方法的参数和返回值类型都是Consumer类型,那么就可以实现效果:消费数据的时候,首先做一个操作,然后再做一个操作,实现组合。而这个方法就是Consumer接口中的default方法andThen。

要想实现组合,需要两个或多个Lambda表达式即可,而 andThen的语义正是一步接一步操作。例如两个步骤组合的情况:

1
2
3
4
Consumer<Author> consumer1 = s -> System.out.print("作家名:" + s.getName());
Consumer<Author> consumer2 = s -> System.out.println("作家介绍:" + s.getIntro());
Author author = new Author(1L, "蒙多", 33, "一个从菜刀中明悟哲理的祖安人", null);
consumer1.andThen(consumer2).accept(author);

Predicate接口

有时候我们需要对某种类型的数据进行判断,从而达到一个Boolean值结果,这时可以使用 java.util.function.Predicate接口。

抽象方法:test

Predicate接口中包含一个抽象方法:boolean test(T t).用于条件判断的场景:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package com.Lambda;

import java.util.function.Predicate;

public class PredicateDemo {
/*
* 定义一个方法:
* 参数传递一个Author类型的字符串,传递一个predicate接口,泛型使用Author
* 使用predicate中的方法test对字符串进行判断,并把判断的结果返回
* */
public static Boolean checkAge(Author author, Predicate<Author> pre){
return pre.test(author);
}

public static void main(String[] args) {
Author menduo = new Author(1L, "蒙多", 33, "一个从菜刀中明悟哲理的祖安人", null);
boolean b1 = checkAge(menduo ,(Author author)->{
return author.getAge() > 17;
});
boolean b2 = checkAge(menduo ,author -> author.getAge() > 17);
System.out.println(b2);
}
}
默认方法:and

and(Predicate<? super T> other),我们在使用Predicate接口时候可能需要进行判断条件的拼接。而and方法相当于是使用&&来拼接两个判断条件

例如:打印作家中年龄大于17并且姓名的长度大于1的作家。

1
2
3
4
5
6
// 打印作家中年龄大于17并且姓名的长度大于1的作家。
List<Author> authors = getAuthors();
authors.stream()
.filter(((Predicate<Author>) author -> author.getAge() > 17)
.and(author -> author.getName().length() > 1))
.forEach(System.out::println);
默认方法:or

or(Predicate<? super T> other),我们在使用Predicate接口时候可能需要进行判断条件的拼接。而or方法相当于是使用||来拼接两个判断条件。

例如:打印作家中年龄大于17或者姓名的长度小于2的作家。

1
2
3
4
5
6
// 打印作家中年龄大于17或者姓名的长度小于2的作家。
List<Author> authors = getAuthors();
authors.stream()
.filter(((Predicate<Author>) author -> author.getAge() > 17)
.or(author -> author.getName().length()<2))
.forEach(author -> System.out.println(author.getName()));
默认方法:negate

Predicate接口中的方法。negate方法相当于是在判断添加前面加了个! 表示取反

例如:打印作家中年龄不大于17的作家。

1
2
3
4
5
// 打印作家中年龄不大于17的作家。
List<Author> authors = getAuthors();
authors.stream()
.filter(((Predicate<Author>) author -> author.getAge() > 17).negate())
.forEach(author -> System.out.println(author.getAge()));

Function接口

java.util.function.Function<T,R>接口用来根据一个类型得到另一个类型的数据,前者称为前置条件,后者称为后置条件。

Function接口中最主要的抽象方法为:R apply(T t),根据类型T的参数获取类型R的结果。

使用的场景例如:将 String类型转换为 Integer类型。

  • 默认方法 compose(Function<? super V, ? extends T> before),先执行compose方法参数before中的apply方法,然后将执行结果传递给调用compose函数中的apply方法在执行。
  • andThen(Function<? super R, ? extends V> after),先执行调用andThen函数的apply方法,然后在将执行结果传递给andThen方法after参数中的apply方法在执行。它和compose方法整好是相反的执行顺序。
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
 public class FunctionDemo {
/*
* 定义一个方法:方法的参数传递一个字符串类型的整数,一个Function接口,泛型使用<Integer,String>
* 使用Function接口中的方法apply,把Integer类型的整数,转换成字符串
*/
private static void convert(Integer i, Function<Integer, String> fun) {
String s = fun.apply(i);
System.out.println(s);
}

private static void convert(Integer i, Function<Integer, String> fun1, Function<String, String> fun2) {
String str = fun1.andThen(fun2).apply(i);
System.out.println(str);
}

private static void convert(String s, Function<String, Integer> fun1, Function<Integer, String> fun2) {
String str = fun2.compose(fun1).apply(s);
System.out.println(str);
}


public static void main(String[] args) {
convert(666, i -> String.valueOf(i));
convert(666, i -> String.valueOf(i), s -> "快手-" + s);
convert("666", s -> Integer.parseInt(s), s -> "快手-" + s);
}
}

6. 方法引用

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

我们在使用lambda时不需要考虑什么时候用方法引用,用哪种方法引用,方法引用的格式是什么,我们只需要在写完lambda方法发现方法体只有一行代码,并且是方法的调用时使用快捷键尝试是否能够转换成方法引用即可,当我们方法引用使用的多了慢慢的也可以直接写出方法引用。

基本格式

类名或者对象名::方法名

语法详解

引用类的静态方法

其实就是引用类的静态方法

格式: 类名::方法名

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

例如:如下代码就可以用方法引用进行简化

1
2
3
4
List<Author> authors = getAuthors();
Stream<Author> authorStream = authors.stream();
authorStream.map(author -> author.getAge())
.map(age -> String.valueOf(age));

注意,如果我们所重写的方法是没有参数的,调用的方法也是没有参数的也相当于符合以上规则。

优化后如下:

1
2
3
4
List<Author> authors = getAuthors();
Stream<Author> authorStream = authors.stream();
authorStream.map(author -> author.getAge())
.map(String::valueOf);

引用对象的实例方法

格式:对象名::方法名

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

例如:

1
2
3
4
List<Author> authors = getAuthors();
Stream<Author> authorStream = authors.stream();
StringBuilder sb = new StringBuilder();
authorStream.map(author -> author.getName()).forEach(name->sb.append(name));

优化后:

1
2
3
4
List<Author> authors = getAuthors();
Stream<Author> authorStream = authors.stream();
StringBuilder sb = new StringBuilder();
authorStream.map(author -> author.getName()).forEach(sb::append);

引用类的实例方法

格式:类名::方法名

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

例如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
interface UseString{
String use(String str,int start,int length);
}

public static String subAuthorName(String str, UseString useString){
int start = 0;
int length = 1;
return useString.use(str,start,length);
}
public static void main(String[] args) {
subAuthorName("快手科技", new UseString() {
@Override
public String use(String str, int start, int length) {
return str.substring(start,length);
}
});
}

优化后如下:

1
2
3
public static void main(String[] args) {
subAuthorName("快手科技", String::substring);
}

构造器引用

如果方法体中的一行代码是构造器的话就可以使用构造器引用。

格式:类名::new

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

例如:

1
2
3
4
5
6
List<Author> authors = getAuthors();
authors.stream()
.map(author -> author.getName())
.map(name -> new StringBuilder(name))
.map(sb -> sb.append("-快手").toString())
.forEach(str-> System.out.println(str));

优化后:

1
2
3
4
5
6
List<Author> authors = getAuthors();
authors.stream()
.map(author -> author.getName())
.map(StringBuilder::new)
.map(sb->sb.append("-快手").toString())
.forEach(str-> System.out.println(str));

Java的函数式编程能力在Java 8及以后的版本中得到了极大的增强,函数式接口、Lambda表达式和方法引用使得编写函数式风格的代码变得更加容易和优雅。了解函数式接口的概念以及如何使用它们是成为Java高级程序员的重要一步。希望本文能够帮助您更好地理解和应用Java的函数式编程特性。