16-Java8的其他新特性

16—Java8的其他新特性

16-Java8新特性

1. Lambda表达式

Lambda是一个匿名函数,我们可以把Lambda表达式理解为是一段可以传递的代码(将代码像数据一样进行传递)。使用它可以写出更简洁、更灵活的代码。作为一种更紧凑的代码风格,使Java语言表达能力得到了提升

  • 从匿名类到Lambda的转换举例1

    1
    2
    3
    4
    5
    6
    7
    //匿名内部类
    Runnable r1 = new Runnable(){
    @Override
    public void run(){
    System.out.println("hello world!");
    }
    };
    1
    2
    //Lambda表达式
    Runnable r1 = () -> System.out.println("hello world!");
  • 从匿名类到Lambda的转换举例2

    1
    2
    3
    4
    5
    6
    7
    //原来使用匿名内部类作为参数传递
    TreeSet<String> ts = new TreeSet<>(new Comparator<String>(){
    @Override
    public int compare(String o1, String o2){
    return Integer.compare(o1.length(),o2.length())
    }
    });
    1
    2
    3
    4
    //Lambda 表达式作为参数传递
    TreeSet<String> ts2 = new TreeSet<>(
    (o1,o2) -> Integer.compare(o1.length(), o2.length())
    );

Lambda表达式:在Java8语言中引入的一种新的语法元素和操作符。这个操作符为“->”,该操作符被称为Lambda操作符或箭头操作符。他将Lambda分为两个部分:

左侧:指定了Lambda表达式需要的参数列表

右侧:指定了Lambda体,是抽象方法的实现逻辑,也即Lambda表达式要执行的功能

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//语法格式一:无参,无返回值
Runnable r1= ()->{System.out.println("Hello Lambda");};
//语法格式二:Lambda需要一个参数,但是没有返回值
Consumer<String> con = (String str) -> {System.out.println(str);};
//语法格式三:数据类型可以省略,因为可以由编译器推断得出,称为“类型推断”
Consumer<String> con = (str) -> {System.out.println(str);};
//语法格式四:Lambda只需要一个参数时,参数的小括号可以省略
Consumer<String> con = str -> {System.out.println(str);};
//语法格式五:Lambda需要两个或以上的参数,多条执行语句,并且可以有返回值
Comparator<Integer> com = (x,y) -> {
System.out.println("实现函数式接口方法");
return Integer.compare(x,y);
};
//语法格式六:当Lambda体只有一条语句时,return与大括号若有,都可以省略
Comparator<Integer> com = (x,y) -> Integer.compare(x,y);

类型推断

上述Lambda表达式中的参数类型都是由编译器推断得出的。Lambda表达式中无需指定类型,程序依然可以编译,这是因为javac根据程序的上下文,在后台推断出了参数的类型。Lambda表达式的类型依赖于上下文的环境,是由编译器推断出来的。

image-20210807153542725

1.1 示例
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
package Lambda表达式;

import org.junit.Test;

import java.util.Comparator;

public class LambdaTest1 {
@Test
public void test1(){
Runnable r1 = new Runnable() {
@Override
public void run() {
System.out.println("我在花江学计算机");
}
};

r1.run();

System.out.println("|+++++++++++++++++++++|");

Runnable r2 = () -> System.out.println("I love GUET");
r2.run();

}

@Test
public void test2(){
Comparator<Integer> com1 = new Comparator<Integer>(){
@Override
public int compare(Integer o1, Integer o2) {
return Integer.compare(o1,o2);
}
};
int compare1 = com1.compare(12,21);
System.out.println(compare1);

System.out.println("|++++++++++++++++++++++++++|");
//Lambda表达式写法
Comparator<Integer> com2 = (o1,o2) -> Integer.compare(o1,o2);
int compare2 = com2.compare(12,21);
System.out.println(compare2);

System.out.println("|++++++++++++++++++++++++++|");
//方法引用
Comparator<Integer> com3 = Integer :: compare;
int compare3 = com3.compare(12,21);
System.out.println(compare3);
}
}

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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
package Lambda表达式;

import org.junit.Test;

import java.util.Comparator;
import java.util.function.Consumer;

/*
Lambda表达式的使用
1.举例:(o1, o2) -> Integer.compare(o1, o2);
2.格式:
-:lambda操作符
-:左边:lambda形参列表(其实就是接口中的抽象方法的新参列表)
-:右边:lambda体(其实就是重写抽象方法的方法体)

3.Lambda表达式的使用:(分为六种情况)
总结:
-:左边:lambda形参列表的参数类型可以省略(类型推断);如果lambda形参列表只有一个参数,其中一堆()也可以省略
-:右边:lambda体应该使用一对{}包裹;如果lambda体只有一条执行语句(可能是return语句),省略这一对{}和return关键字

4.Lambda表达式的本质:作为函数式接口的实例

5.如果一个接口中,只声明了一个抽象方法,则此接口就称为函数式接口。我们可以在一个接口上使用@FunctionalInterface注解。
这样就可以做检查它是否是一个函数式接口

6.所以以前使用匿名实现类表示的现在都可以用Lambda表达式来写
*/
public class LambadTest2 {

//语法格式一:无参无返回值
@Test
public void test1(){
Runnable r1 = new Runnable() {
@Override
public void run() {
System.out.println("我在金鸡岭写代码");
}
};
r1.run();

System.out.println("|+++++++++++++++++++++|");

Runnable r2 = () -> {System.out.println("我在金鸡岭写代码");};
r2.run();
}

//语法格式二:Lambda需要一个参数,但是没有返回值 正常写法
@Test
public void test2(){
Consumer<String> con = new Consumer<String>() {
@Override
public void accept(String s) {
System.out.println(s);
}
};
con.accept("你在哪儿");

System.out.println("|+++++++++++++++++++++|");

Consumer<String> con2 = (String s) ->{System.out.println(s); } ;
con2.accept("我在这儿");
}

//语法格式三:Lambda需要一个参数,但是没有返回值 数据类型可以省略,因为可以由编译器推断得出,称为”类型推断“
@Test
public void test3(){
Consumer<String> con = new Consumer<String>() {
@Override
public void accept(String s) {
System.out.println(s);
}
};
con.accept("你在哪儿");

System.out.println("|+++++++++++++++++++++|");

Consumer<String> con2 = (s) ->{System.out.println(s); } ;
con2.accept("我在这儿");
}

//语法格式四:Lambda需要一个参数,但是没有返回值 数据类型可以省略,因为可以由编译器推断得出,称为”类型推断“,参数的小括号也可以省略
@Test
public void test4(){
Consumer<String> con = new Consumer<String>() {
@Override
public void accept(String s) {
System.out.println(s);
}
};
con.accept("你在哪儿");

System.out.println("|+++++++++++++++++++++|");

Consumer<String> con2 = s ->{System.out.println(s); } ;
con2.accept("我在这儿");
}

//语法格式五:Lambda需要一个参数,数据类型可以省略,因为可以由编译器推断得出,称为”类型推断“,参数的小括号也可以省略
//但是没有返回值 只有一条语句,方法体的{}也可以省略
@Test
public void test5(){
Consumer<String> con = new Consumer<String>() {
@Override
public void accept(String s) {
System.out.println(s);
}
};
con.accept("你在哪儿");

System.out.println("|+++++++++++++++++++++|");

Consumer<String> con2 = s ->System.out.println(s);
con2.accept("我在这儿");
}

//语法格式五::Lambda需要两个或以上的参数,多条执行语句,并且可以有返回值
@Test
public void test6(){
Comparator<Integer> com1 = new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
System.out.println(o1);
System.out.println(o2);
return Integer.compare(o1,o2);
}
};
System.out.println(com1.compare(12, 21));

System.out.println("|+++++++++++++++++++++|");
Comparator<Integer> com2 = (o1, o2) -> {
System.out.println(o1);
System.out.println(o2);
return Integer.compare(o1,o2);
};
System.out.println(com2.compare(12, 21));
}

//语法格式六:当Lambda体只有一条语句时,return(若有)与大括号都可以省略;
@Test
public void test7(){
Comparator<Integer> com1 = (o1, o2) -> Integer.compare(o1,o2);
System.out.println(com1.compare(12, 21));
}
}

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
package Lambda表达式;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Predicate;

/*
Java内置的四大核心函数式接口

消费型接口 Consumer<T> void accept(T t)
供给型接口 Supplier<T> T get()
函数型接口 Function<T,R> R apply(T t)
断定型接口 Predicate<T> boolean test(T t)

*/
public class LambdaTest3 {
@Test
public void test1(){
relax("打篮球", new Consumer<String>() {
@Override
public void accept(String s) {
System.out.println("学习太累了," + s + "放松一下");
}
});

relax("看Bilibili",method -> System.out.println("学习太累了,"+method+"放松一下"));
}
public void relax(String method, Consumer<String> con){
con.accept(method);
}

@Test
public void test2(){
List<String> list = Arrays.asList("北京","南京","天津","东京","西京","普京");
List<String> filterStrs = filterString(list, new Predicate<String>() {
@Override
public boolean test(String s) {
return s.contains("京");
}
});
System.out.println(filterStrs);

List<String> filterStr1 = filterString(list,s -> s.contains("京"));
System.out.println(filterStr1);
}

public List<String> filterString(List<String> list, Predicate<String> predicate){
ArrayList<String> filterList = new ArrayList<>();

for (String s : list) {
if(predicate.test(s)){
filterList.add(s);
}
}
return filterList;
}
}

2. 函数式(Functional)接口

2.1 什么是函数式(Funcional)接口
  • 只包含一个抽象方法的接口,称为函数式接口
  • 你可以通过Lambda表达式来创建该接口的对象。(若Lambda表达式抛出一个受检异常(即:非运行时异常),那么该异常需要在目标接口的抽象方法上进行声明)
  • 我们可以在一个接口上使用@FuncionalInterface注解,这样做可以检查它是否是一个函数式接口。同时javadoc也会包含一条声明,说明这个接口是一个函数是接口
  • 在java.util.function包下定义了Java8的丰富的函数式接口
2.2 如何理解函数式接口
  • Java从诞生日起就是一直倡导“一切皆对象”,在Java里面面向对象(OOP) 编程是一切。但是随着python、scala等语言的兴起和新技术的挑战,Java不得不做出调整以便支持更加广泛的技术要求,也即java不但可以支持OOP还 可以支持OOF(面向函数编程)
  • 在函数式编程语言当中,函数被当做一等公民对待。在将函数作为一等公民的编程语言中,Lambda表达式的类型是函数。但是在Java8中,有所不同。在 Java8中,Lambda表达式是对象,而不是函数,它们必须依附于一类特别的对象类型——函数式接口
  • 简单的说,在Java8中,Lambda表达式就是一个函数式接口的实例。这就是 Lambda表达式和函数式接口的关系。也就是说,只要一个对象是函数式接口 的实例,那么该对象就可以用Lambda表达式来表示
  • 所以以前用匿名实现类表示的现在都可以用Lambda表达式来写
2.3 函数式接口举例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@FunctionalInterface
public interface Runnable {
/**
* When an object implementing interface {@code Runnable} is used
* to create a thread, starting the thread causes the object's
* {@code run} method to be called in that separately executing
* thread.
* <p>
* The general contract of the method {@code run} is that it may
* take any action whatsoever.
*
* @see java.lang.Thread#run()
*/
public abstract void run();
}
2.4 自定义函数式接口
1
2
3
4
@FuncitonalInterface
public interface Mynumber{
public double getValue();
}

函数式接口中使用泛型:

1
2
3
4
@FunctionalInterface
public interface MyFunc<t>{
public T getValue(T t);
}
2.5 作为参数传递Lambda表达式

image-20210807155726164

2.6 Java内置四大核心函数式接口
函数式接口 参数类型 返回类型 用途
Consumer 消费型接口 T void 对类型为T的对象应用操作,包含方法:void accept(T t)
Supplier 供给型接口 T 返回类型为T的对象,包含方法:T get()
Function<T,R> 函数类型接口 T R 对类型为T的对象应用操作,并返回结果。结果是R类型的对象。包含方法:R apply(T t)
Predicate 断定型接口 T boolean 确定类型为T的对象是否满足某约束,并返回boolean值。包含方法:boolean test(T t)
2.7 其他接口
函数式接口 参数类型 返回类型 用途
BiFunction<T,U,R> T,U R 对类型为T,U参数应用操作,返回R类型的结果。包含方法为:R apply(T t, U u);
UnaryOperator (Function子接口) T T 对类型为T的对象进行一元运算,并返回T类型的结果。包含方法为:T apply(T t)
BinaryOperator (BiFunction子接口) T,T T 对类型为T的对象进行二元运算,并返回T类型的结果。包含方法为:T apply(T t1, T t2)
BiConsumer<T,U> T,U void 对类型为T,U参数应用操作
包含方法为:void accept(T t, U u)
BiPredicate<T,U> T,U boolean 包含方法为:boolean test(T t, Uu)
ToIntFuction T int 计算int值的函数
ToLongFunction T long 计算long值的函数
ToDoubleFunction T double 计算double值的函数
IntFunction int R 参数为int类型的函数
LongFunction long R 参数为long类型的函数
DoubleFunction double R 参数为double类型的函数

3. 方法引用与构造器引用

3.1 方法引用(Method References)
  • 当要传递给Lambda体的操作时,已经有实现的方法了,可以使用方法引用

  • 方法引用可以看作是Lambda表达式深层次的表达。换句话说,方法引用就是Lambda表达式,也就是函数式接口的一个实例,通过方法的名字来指向一个方法,可以认为是Lambda表达式的一个语法糖

  • 要求:实现接口的抽象方法的参数列表和返回值类型,必须与方法引用的方法的参数列表和返回值类型保持一致

  • 格式:使用操作符“::”将类(或对象)与方法名分隔开

  • 如下三种主要使用情况:

    • 对象::实例方法名
    • 类::静态方法名
    • 类::实例方法名
  • 例如:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    Consumer<String> con = (x) -> System.out.println(x);
    //等同于
    Consume<String> con1 = System.out::println;

    //例如:
    Comparator<Integer> com = (x,y) -> Integer.compare(x,y);
    //等同于
    Comparator<Integer> com1 = Integer::compare;
    int value = com.compare(12,32);

    //例如:
    BiPredicate<String,String> bp = (x,y) -> x.equals(y);
    //等同于
    BiPredicate<String,String> bp1 = String::equals;
    boolean falg= bp1.test("hello","hi");

    注意:当函数式接口方法的第一个参数是需要引用方法的调用者,并且第二 个参数是需要引用方法的参数(或无参数)时:ClassName::methodName

3.2 构造器引用

格式:ClassName::new

与函数式接口相结合,自动与函数式接口中的方法兼容。

可以把构造器引用赋值给定义的方法,要求构造器参数列表要与接口中抽象方法的参数列表一致,且方法的返回值即为构造器对应类的对象

1
2
3
4
//例如
Function<Integer, MyClass> fun = (n) -> new MyClass(n);
//等同于
Function<Integer, MyClass> fun = MyClass::new;
3.3 数组引用

格式:type[]::new

1
2
3
4
//例如
Function<Integer, Integer[]> fun = (n) -> new Integer[n];
//等同于
Function<Integer, Integer[]> fun = Integer[]::new;
3.4 示例

image-20210816214443373

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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package 方法引用与构造器引用;

import java.util.Objects;

public class Employee {
private int id;
private String name;
private int age;
private double salary;

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

public double getSalary() {
return salary;
}

public void setSalary(double salary) {
this.salary = salary;
}

public Employee() {
System.out.println("Employee().....");
}

public Employee(int id) {
this.id = id;
}

public Employee(int id, String name) {
this.id = id;
this.name = name;
}

public Employee(int id, String name, int age, double salary) {
this.id = id;
this.name = name;
this.age = age;
this.salary = salary;
}

@Override
public String toString() {
return "Employee{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", salary=" + salary +
'}';
}

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Employee employee = (Employee) o;
return id == employee.id && age == employee.age && Double.compare(employee.salary, salary) == 0 && Objects.equals(name, employee.name);
}

@Override
public int hashCode() {
return Objects.hash(id, name, age, salary);
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package 方法引用与构造器引用;

import java.util.ArrayList;
import java.util.List;

public class EmployeeData {
public static List<Employee> getEmployee(){
List<Employee> list = new ArrayList<>();

list.add(new Employee(1001, "马化腾", 34, 6000.38));
list.add(new Employee(1002, "马云", 12, 9876.12));
list.add(new Employee(1003, "刘强东", 33, 3000.82));
list.add(new Employee(1004, "雷军", 26, 7657.37));
list.add(new Employee(1005, "李彦宏", 65, 5555.32));
list.add(new Employee(1006, "比尔盖茨", 42, 9500.43));
list.add(new Employee(1007, "任正非", 26, 4333.32));
list.add(new Employee(1008, "扎克伯格", 35, 2500.32));

return list;
}

}

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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
package 方法引用与构造器引用;

import org.junit.Test;

import java.io.PrintStream;
import java.util.Comparator;
import java.util.function.BiPredicate;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;

/*
方法的引用
1.使用情景:当要传递给Lambda体的操作,已经有实现的方法了,可以使用方法引用
2.方法引用,本质上就是Lambda表达式,而Lambda表达式作为函数式接口的实例。所以方法引用也是函数式接口的实例
3.使用格式:类(或对象)::方法名
4.具体分为如下三种情况:
情况1;对象 :: 非静态方法
情况2:类 :: 静态方法
情况3:类 :: 非静态方法
5.方法引用的使用要求:要求接口中的抽象方法的形参列表和返回值类类型与方法引用的形参列表和返回值类型相同(针对情况1和2)
*/
public class MethodRefTest {

//情况一:对象 :: 实例方法
//Consumer中的void accept(T t)
//PrintStream中的void println(T t)
@Test
public void test1(){
Consumer<String> con = str -> System.out.println(str);
con.accept("花江");

System.out.println("|+++++++++++++++++++++|");
PrintStream ps = System.out;
Consumer<String> con1 = ps :: println;
con1.accept("金鸡岭");
}

//Supplier中的T get()
//Employee中的String getName()
@Test
public void test2(){
Employee emp = new Employee(1001,"xiong",23,15000);

Supplier<String > supplier = () -> emp.getName();
System.out.println(supplier.get());

System.out.println("|+++++++++++++++++++++|");
Supplier<String> stringSupplier = emp :: getName;
System.out.println(stringSupplier.get());
}

//情况二:类 :: 静态方法
//Comparator中的int compare(T t1, T t2)
//Interger中的int comapra(T t1, T t2)
@Test
public void test3(){
Comparator<Integer> com1 = (t1,t2) -> Integer.compare(t1,t2);
System.out.println(com1.compare(12, 21));

System.out.println("|+++++++++++++++++++++|");

Comparator<Integer> com2 = Integer :: compare;
System.out.println(com2.compare(12, 21));
}

//Function中的R apply(T t)
//Math中的Long round(double d)
@Test
public void test4(){
Function<Double,Long> func = new Function<Double, Long>() {
@Override
public Long apply(Double aDouble) {
return Math.round(aDouble);
}
};
System.out.println(func.apply(12.8));

System.out.println("|+++++++++++++++++++++|");
Function<Double,Long> func1 = d -> Math.round(d);
System.out.println(func1.apply(12.3));

System.out.println("|+++++++++++++++++++++|");
Function<Double,Long> func2 = Math :: round;
System.out.println(func2.apply(12.4));
}

//情况三:类 :: 实例方法
//Comparator中的int compare(T t1, T t2)
//String中的int t1.compareTo(t2)
@Test
public void test5(){
Comparator<String> com1 = (s1, s2) -> s1.compareTo(s2);
System.out.println(com1.compare("abc", "abd"));

System.out.println("|+++++++++++++++++++++|");
Comparator<String> com2 = String :: compareTo;
System.out.println(com2.compare("abc", "abd"));
}

//BiPredicate中的boolean test(T t1, T t2);
//String中的boolean t1.equals(t2)
@Test
public void test6(){
BiPredicate<String,String> pre1 = (s1,s2) ->s1.equals(s2);
System.out.println(pre1.test("ab", "ab"));

System.out.println("|+++++++++++++++++++++|");
BiPredicate<String,String> pre2 = String :: equals;
System.out.println(pre2.test("ax", "az"));
}

//Fuction中的R apply(T t) 传一个参数,返回另一个数据
//Employee中的String T.getName();
@Test
public void test7(){
Employee employee = new Employee(1001,"zhuo",23,15000);

Function<Employee,String> fun1 = e -> e.getName();
System.out.println(fun1.apply(employee));

System.out.println("|+++++++++++++++++++++|");
Function<Employee,String> fun2 = Employee :: getName;
System.out.println(fun2.apply(employee));
}
}

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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package 方法引用与构造器引用;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Supplier;

/*
一、构造器引用
和方法引用类似,函数式接口的抽象方法的形参列表和构造器的形参列表一致。
抽象方法的返回值类型即为构造器所属的类的类型
二、数组引用
大家可以把数组看作是一个特殊的类。则写法与构造器引用一致

*/
public class ConstructorTest {
//构造器引用
//Supperlier中的T get()
//Employee的空参构造器:Employee()
@Test
public void test1(){
Supplier<Employee> sup = new Supplier<Employee>() {
@Override
public Employee get() {
return new Employee();
}
};
System.out.println(sup.get());

System.out.println("|+++++++++++++++++++++|");
Supplier<Employee> sup1 = () -> new Employee();
System.out.println(sup1.get());

System.out.println("|+++++++++++++++++++++|");
Supplier<Employee> sup2 = Employee::new;
System.out.println(sup2.get());
}

//Function中的R apply(T t)
@Test
public void test2(){
Function<Integer,Employee> func1 = id -> new Employee(id);
Employee em1 = func1.apply(1002);
System.out.println(em1);

System.out.println("|+++++++++++++++++++++|");
Function<Integer,Employee> func2 = Employee :: new;
System.out.println(func2.apply(1003));
}

//BiFunction中的R apply(T t, U u)
@Test
public void test3(){
BiFunction<Integer,String,Employee> func1 = (id,name) -> new Employee(id,name);
System.out.println(func1.apply(1004, "xiong"));

System.out.println("|+++++++++++++++++++++|");
BiFunction<Integer,String,Employee> func2 = Employee::new;
System.out.println(func2.apply(1005, "zhuo"));
}

//数组引用
//Function中的R apply(T t)
@Test
public void test4(){
Function<Integer,String[]> func1 = length -> new String[length];
String[] arr1 = func1.apply(10);
System.out.println(Arrays.toString(arr1));

System.out.println("|+++++++++++++++++++++|");
Function<Integer,String[]> func2 = String[] :: new;
String[] arr2 = func2.apply(10);
System.out.println(Arrays.toString(arr2));
}
}

4. 强大的Stream API

4.1 Stream API说明
  • Java8中有两大最为重要的改变。第一个是 Lambda 表达式;另外一个则是 Stream API。
  • Stream API ( java.util.stream) 把真正的函数式编程风格引入到Java中。这是目前为止对Java类库最好的补充,因为Stream API可以极大提高Java程序员的生产力,让程序员写出高效率、干净、简洁的代码。
  • Stream 是Java8 中处理集合的关键抽象概念,它可以指定你希望对集合进行的操作,可以执行非常复杂的查找、过滤和映射数据等操作。 使用 Stream API 对集合数据进行操作,就类似于使用 SQL 执行的数据库查询。 也可以使用 Stream API 来并行执行操作。简言之,Stream API 提供了一种高效且易于使用的处理数据的方式。
4.2 为什么要使用Stream API
  • 实际开发中,项目中多数数据源都来自于Mysql,Oracle等。但现在数据源可以更多了,有MongDB,Radis等,而这些NoSQL的数据就需要 Java层面去处理。
  • Stream 和 Collection 集合的区别:Collection 是一种静态的内存数据 结构,而 Stream 是有关计算的。前者是主要面向内存,存储在内存中, 后者主要是面向 CPU,通过 CPU 实现计算。
4.3 什么是Stream

Stream到底是什么呢?

是数据渠道,用于操作数据源(集合、数组等)所生成的元素序列。 “集合讲的是数据,Stream讲的是计算!”

注意: ①Stream 自己不会存储元素。 ②Stream 不会改变源对象。相反,他们会返回一个持有结果的新Stream。 ③Stream 操作是延迟执行的。这意味着他们会等到需要结果的时候才执行。

4.4 Stream的操作三个步骤
  • 1- 创建 Stream

    一个数据源(如:集合、数组),获取一个流

  • 2- 中间操作

    一个中间操作链,对数据源的数据进行处理

  • 3- 终止操作(终端操作)

    一旦执行终止操作,就执行中间操作链,并产生结果。之后,不会再被使用

    image-20210807210657432

4.5 创建Stream的方式
4.5.1 方式一:通过集合

Java8 中的 Collection 接口被扩展,提供了两个获取流的方法:

  • default Stream stream() : 返回一个顺序流
  • default Stream parallelStream() : 返回一个并行流
4.5.2 方式二:通过数组

Java8 中的 Arrays 的静态方法 stream() 可以获取数组流:

  • static Stream stream(T[] array): 返回一个流
  • 重载形式,能够处理对应基本类型的数组:
    • public static IntStream stream(int[] array)
    • public static LongStream stream(long[] array)
    • public static DoubleStream stream(double[] array)
4.5.3 方式三:通过Stream的of()

可以调用Stream类静态方法of(),通过显示值创建一个流。它可以接收任意数量的参数

  • public static Stream of(T… values) : 返回一个流
4.5.4 方式四:创建无限流

可以使用静态方法 Stream.iterate() 和 Stream.generate(), 创建无限流。

  • 迭代

    public static Stream iterate(final T seed, final UnaryOperator f)

  • 生成

    public static Stream generate(Supplier s)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 方式四:创建无限流
@Test
public void test4() {
// 迭代
// public static<T> Stream<T> iterate(final T seed, final
// UnaryOperator<T> f)
Stream<Integer> stream = Stream.iterate(0, x -> x + 2);
stream.limit(10).forEach(System.out::println);
// 生成
// public static<T> Stream<T> generate(Supplier<T> s)
Stream<Double> stream1 = Stream.generate(Math::random);
stream1.limit(10).forEach(System.out::println);
}

4.6 Stream的中间操作

多个中间操作可以连接起来形成一个流水线,除非流水线上触发终止操作,否则中间操作不会执行任何的处理。而在中止操作时一次性全部处理,称为“惰性求值”

1-筛选与切片

方法 描述
filter(Predicate p) 接收Lambda,从流中排除某些元素
distinct() 筛选,通过流所生成元素的hashCode()和equals()去除重复元素
limit(long maxSize) 截断流,使其元素不超过给定数量
skip(long n) 跳过元素,返回一个扔掉了前n个元素的流。若流中元素不足n个,则返回了一个空流。与limit(n)互补

2-映射

方法 描述
map(Function f) 接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素。
mapToDouble(ToDoubleFunction f) 接收一个函数作为参数,该函数会被应用到每个元素上,产生一个新的 DoubleStream。
mapToInt(ToIntFunction f) 接收一个函数作为参数,该函数会被应用到每个元素上,产生一个新的 IntStream。
mapToLong(ToLongFunction f) 接收一个函数作为参数,该函数会被应用到每个元素上,产生一个新的 LongStream。
flatMap(Function f) 接收一个函数作为参数,将流中的每个值都换成另 一个流,然后把所有流连接成一个流。

3-排序

方法 描述
sorted() 产生一个新流,其中按自然顺序排序
sorted(Comparator com) 产生一个新流,其中按比较器顺序排序
4.7 Streasm的终止操作
  • 终端操作会从流的流水线生成结果。其结果可以是任何不是流的值,例 如:List、Integer,甚至是 void 。
  • 流进行了终止操作后,不能再次使用。

1-匹配与查找

方法 描述
allMatch(Predicate p) 检查是否匹配所有元素
anyMatch(Predicate p) 检查是否至少匹配一个元素
noneMatch(Predicate p) 检查是否没有匹配所有元素
findFirst() 返回第一个元素
findAny() 返回当前流中的任意元素
count() 返回流中元素总数
max(Comparator c) 返回流中最大值
min(Comparator c) 返回流中最小值
forEach(Consumer c) 内部迭代(使用 Collection 接口需要用户去做迭代, 称为外部迭代。相反,Stream API 使用内部迭 代——它帮你把迭代做了)

2-规约

方法 描述
reduce(T iden, BinaryOperator b) 可以将流中元素反复结合起来,得到一 个值。返回 T
reduce(BinaryOperator b) 可以将流中元素反复结合起来,得到一 个值。返回 Optional

备注:map 和 reduce 的连接通常称为 map-reduce 模式,因 Google 用它来进行网络搜索而出名。

3-收集

方法 描述
collect(Collector c) 将流转换为其他形式。接收一个 Collector 接口的实现,用于给Stream中元素做汇总 的方法

Collector 接口中方法的实现决定了如何对流执行收集的操作(如收集到 List、Set、 Map)。另外, Collectors 实用类提供了很多静态方法,可以方便地创建常见收集器实例, 具体方法与实例如下表:

image-20210807222605618

image-20210807222624794

4.8 示例
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
63
64
65
66
67
68
69
70
71
package StreamAPI;

import org.junit.Test;
import 方法引用与构造器引用.Employee;
import 方法引用与构造器引用.EmployeeData;

import java.util.Arrays;
import java.util.List;
import java.util.stream.IntStream;
import java.util.stream.Stream;

/*
1.Stream关注的是对数据的运算,与CPU打交道,集合关注的的是数据的存储
2.
①Stream 自己不会存储元素
②Stream 不会改变源对象,相反,他们会返回一个持有结果的新Stream
③Stream 操作是延迟执行的。这意味着他们会等到徐娅结果的时候才执行
3.Stream执行流程
①Stream的实例化
②一系列的中间操作(过滤、映射)
③终止操作
4.说明:
4.1 一个中间操作链,对数据源的数据进行处理
4.2 一旦执行终止操作,就执行中间操作链,并产生结果。之后,不会再被使用

测试Stream的实例化
*/
public class StreamAPITest {
//创建Stream方式一:通过集合
@Test
public void test1(){
List<Employee> employeeList = EmployeeData.getEmployee();
//default Stream<E> stream():返回一个顺序流
Stream<Employee> stream = employeeList.stream();
//default Stream<E> parallelStream():返回一个并行流
Stream<Employee> paralleStream = employeeList.parallelStream();
}

//创建方式二:通过数组
@Test
public void test2(){
int[] arr = new int[]{1,2,3,4,5,6};
//调用Arrays类的static<T> Stream<T> stream(T[] array):返回一个流
IntStream stream = Arrays.stream(arr);

Employee e1 = new Employee(1001,"Tom");
Employee e2 = new Employee(102,"Jerry");
Employee[] arr1 = new Employee[]{e1,e2};
Stream<Employee> stream1 = Arrays.stream(arr1);
}

//创建方式三:通过Stream的of()
@Test
public void test3(){
Stream<Integer> stream = Stream.of(1,2,3,4,5,6);
}

//创建方式四:创建无限流
@Test
public void test4(){
//迭代
//public static<T> Stream<T> iterate(final T seed, final UnaryOperator<T> f)
//遍历前10个偶数
Stream.iterate(0,t->t+2).limit(10).forEach(System.out::println);

//生成
//public static<T> Stream<T> generate(Supplier<T> s)
Stream.generate(Math::random).limit(10).forEach(System.out::println);
}
}

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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package StreamAPI;

import org.junit.Test;
import 方法引用与构造器引用.Employee;
import 方法引用与构造器引用.EmployeeData;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

public class StreamAPITest1 {
//1-筛选与切片
@Test
public void test1(){
List<Employee> list = EmployeeData.getEmployee();
//排除元素:filter(Predicate p)——接收Lambda,从流中排除某些元素
Stream<Employee>stream = list.stream();
//练习:查询员工表中薪资大于7000的员工信息
stream.filter(e -> e.getSalary()>7000).forEach(System.out::println);

System.out.println();
//截断流:limt(n)使其元素不超过给定数量
list.stream().limit(2).forEach(System.out::println);
System.out.println();

//跳过元素:skip(n)返回一个扔掉了前n个元素的流。若流中元素不足n个,则返回一个空流。与limit(n)互补
list.stream().skip(2).forEach(System.out::println);
System.out.println();

//筛选元素:distinct()——筛选,通过流所生成元素的hashCode()和equals()去除重复元素
list.add(new Employee(1010,"刘强东",40,8000));
list.add(new Employee(1010,"刘强东",41,8000));
list.add(new Employee(1010,"刘强东",40,8000));
list.add(new Employee(1010,"刘强东",40,8000));
list.add(new Employee(1010,"刘强东",40,8000));
list.stream().distinct().forEach(System.out::println);
}

//2.映射
@Test
public void test2(){
//map(Function f)——接收一个函数作为参数,将元素转换成其他形式的值或者提取信息,该函数会被引用到每个元素上,并将其映射成一个新的元素
List<String> stringList = Arrays.asList("aa","bb","cc","dd");
stringList.stream().map(String :: toUpperCase).forEach(System.out::println);
System.out.println();

//练习1:将流中的每个值都换成另一个流,然后把所有流连接成一个流。
//方式一
Stream<Stream<Character>> streamStream = stringList.stream().map(StreamAPITest1::fromStringToStream);
streamStream.forEach(s -> s.forEach(System.out::println));
System.out.println();
//方式二:
Stream<Character> stream = stringList.stream().flatMap(StreamAPITest1::fromStringToStream);
stream.forEach(System.out::println);
System.out.println();

//练习2:获取员工姓名长度大于3的员工姓名
List<Employee> employeeList = EmployeeData.getEmployee();
Stream<String> nameStream = employeeList.stream().map(Employee :: getName);
nameStream.filter(s -> s.length()>3).forEach(System.out::println);
System.out.println();

}
public static Stream<Character> fromStringToStream(String str){
ArrayList<Character> list = new ArrayList<>();
for (Character c :
str.toCharArray()) {
list.add(c);
}
return list.stream();
}

@Test
public void test3(){
ArrayList list1 = new ArrayList();
list1.add(1);
list1.add(2);
list1.add(3);

ArrayList list2 = new ArrayList();
list2.add(4);
list2.add(5);
list2.add(6);

// list1.add(list2);
list1.addAll(list2);
System.out.println(list1);

}

@Test
public void test4(){
//自然排序
List<Integer> list = Arrays.asList(12,21,78,34,32,54,0,-3);
list.stream().sorted().forEach(System.out::println);

//sorted(Comprator com)——定制排序
List<Employee> list1 = EmployeeData.getEmployee();
list1.stream().sorted((e1,e2) -> {
int ageValue = Integer.compare(e1.getAge(),e2.getAge());
if(ageValue != 0){
return ageValue;
}else {
return - Double.compare(e1.getSalary(),e2.getSalary());
}
}).forEach(System.out::println);
}
}

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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package StreamAPI;

import org.junit.Test;
import 方法引用与构造器引用.Employee;
import 方法引用与构造器引用.EmployeeData;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/*
测试Stream的终止操作
*/
public class StreamTest2 {
//1.匹配与查找
@Test
public void test1(){
List<Employee> employeeList = EmployeeData.getEmployee();

//allMatch(Predicate p)——检查是否匹配所有元素
//练习:是否所有员工年龄都大于18
boolean allMatch = employeeList.stream().allMatch(employee -> employee.getAge() >18);
System.out.println(allMatch);

//anyMatch(Predicate p)——检查是否至少匹配一个元素
//练习:是否存在员工工资大于10000
boolean anyMatch = employeeList.stream().anyMatch(employee -> employee.getSalary()>10000);
System.out.println(anyMatch);

//noneMatch(Predicate p)——检查是否没有匹配元素
//练习:是否存在员工姓名姓“雷”
boolean noneMatch = employeeList.stream().noneMatch(s -> s.getName().startsWith("类"));
System.out.println(noneMatch);

//findFirst——返回第一个元素
Optional<Employee> first = employeeList.stream().findFirst();
System.out.println(first);

//findAny——返回当前流中的任意元素
Optional<Employee> any = employeeList.stream().findAny();
System.out.println(any);
}

@Test
public void test2(){
List<Employee> employeeList = EmployeeData.getEmployee();

//count——返回流中元素的总个数
long count = employeeList.stream().count();
System.out.println(count);//8

//max(Comparator c)——返回流中最大值
//返回最高工资
Stream<Double> salaryStream = employeeList.stream().map(e -> e.getSalary());
Optional<Double> maxSalary = salaryStream.max(Double::compare);
System.out.println(maxSalary);

//min(Comparator c)——返回流中最小值
//返回最低工资
Stream<Double> salary = employeeList.stream().map(e -> e.getSalary());
Optional<Double> minSalary= salary.min(Double::compare);
System.out.println(minSalary);

//forEach(Consumer c)——内部迭代
employeeList.stream().forEach(System.out::println);

//使用集合遍历操作
employeeList.forEach(System.out::println);
}

//2-规约
@Test
public void test3(){
//reduce(T identity, BinaryOperator)——可以将流中的元素反复结合起来,得到一个值。返回T
//练习1:计算1-10的自然数的和
List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
Integer sum = list.stream().reduce(0,Integer :: sum);
System.out.println(sum);

//reduce(BinaryOperator)——可以将流中的元素反复结合起来,得到一个值。返回Optional<T>
//练习2:计算公司所有员工工资的总和
List<Employee> employeeList = EmployeeData.getEmployee();
Stream<Double> saralyStream = employeeList.stream().map(e -> e.getSalary());
Optional<Double> sumSalary = saralyStream.reduce((s1,s2)->s1 + s2);
System.out.println(sumSalary.get());//48424.08 不用.get会输出Optional[48424.08]
}

//3-收集
@Test
public void test(){
//collect(Collector c)——将流转化为其他形式。接收一个Collection接口的实现类,用于给Stream中元素做汇总的方法
//查找工资大于6000的员工,结果返回为一个List或Set
List<Employee> employees = EmployeeData.getEmployee();
List<Employee> employeeList = employees.stream().filter(e -> e.getSalary()>6000).collect(Collectors.toList());
employeeList.forEach(System.out::println);
System.out.println();

Set<Employee> employeeSet = employees.stream().filter(e -> e.getSalary()>6000).collect(Collectors.toSet());
employeeSet.forEach(System.out::println);
}
}

5. Optional类

  • 到目前为止,臭名昭著的空指针异常是导致Java应用程序失败的最常见原因。 以前,为了解决空指针异常,Google公司著名的Guava项目引入了Optional类, Guava通过使用检查空值的方式来防止代码污染,它鼓励程序员写更干净的代 码。受到Google Guava的启发,Optional类已经成为Java 8类库的一部分。
  • Optional 类(java.util.Optional) 是一个容器类,它可以保存类型T的值,代表这个值存在。或者仅仅保存null,表示这个值不存在。原来用 null 表示一个值不 存在,现在 Optional 可以更好的表达这个概念。并且可以避免空指针异常。
  • Optional类的Javadoc描述如下:这是一个可以为null的容器对象。如果值存在 则isPresent()方法会返回true,调用get()方法会返回该对象。
  • Optional提供很多有用的方法,这样我们就不用显式进行空值检测
  • 创建Optional类对象的方法:
    • Optional.of(T t) : 创建一个 Optional 实例,t必须非空;
    • Optional.empty() : 创建一个空的 Optional 实例
    • Optional.ofNullable(T t):t可以为null
  • 判断Optional容器中是否包含对象:
    • boolean isPresent() : 判断是否包含对象
    • void ifPresent(Consumer consumer) :如果有值,就执行Consumer 接口的实现代码,并且该值会作为参数传给它。
  • 获取Optional容器的对象:
    • T get(): 如果调用对象包含值,返回该值,否则抛异常
    • T orElse(T other) :如果有值则将其返回,否则返回指定的other对象。
    • T orElseGet(Supplier other) :如果有值则将其返回,否则返回由 Supplier接口实现提供的对象。
    • T orElseThrow(Supplier exceptionSupplier) :如果有值则将其返 回,否则抛出由Supplier接口实现提供的异常。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Test
public void test1() {
Boy b = new Boy("张三");
Optional<Girl> opt = Optional.ofNullable(b.getGrilFriend());
// 如果女朋友存在就打印女朋友的信息
opt.ifPresent(System.out::println);
}
@Test
public void test2() {
Boy b = new Boy("张三");
Optional<Girl> opt = Optional.ofNullable(b.getGrilFriend());
// 如果有女朋友就返回他的女朋友,否则只能欣赏“嫦娥”了
Girl girl = opt.orElse(new Girl("嫦娥"));
System.out.println("他的女朋友是:" + girl.getName());
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Test
public void test3(){
Optional<Employee> opt = Optional.of(new Employee("张三", 8888));
//判断opt中员工对象是否满足条件,如果满足就保留,否则返回空
Optional<Employee> emp = opt.filter(e -> e.getSalary()>10000);
System.out.println(emp);
}
@Test
public void test4(){
Optional<Employee> opt = Optional.of(new Employee("张三", 8888));
//如果opt中员工对象不为空,就涨薪10%
Optional<Employee> emp = opt.map(
e -> {e.setSalary(e.getSalary()%1.1);return e;});
System.out.println(emp);
}

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
package Optional类;


public class Boy {
private Girl girl;

@Override
public String toString() {
return "Boy{" +
"girl=" + girl +
'}';
}

public Girl getGirl() {
return girl;
}

public void setGirl(Girl girl) {
this.girl = girl;
}

public Boy() {

}

public Boy(Girl girl) {

this.girl = girl;
}
}

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
package Optional类;

public class Girl {

private String name;

@Override
public String toString() {
return "Girl{" +
"name='" + name + '\'' +
'}';
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Girl() {

}

public Girl(String name) {

this.name = name;
}
}

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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package Optional类;

import org.junit.Test;

import java.util.Optional;

/**
* Optional类:为了在程序中避免出现空指针异常而创建的。
*
* 常用的方法:ofNullable(T t)
* orElse(T t)
*
*/
public class OptionalTest {

/*
Optional.of(T t) : 创建一个 Optional 实例,t必须非空;
Optional.empty() : 创建一个空的 Optional 实例
Optional.ofNullable(T t):t可以为null

*/
@Test
public void test1(){
Girl girl = new Girl();
// girl = null;
//of(T t):保证t是非空的
Optional<Girl> optionalGirl = Optional.of(girl);

}

@Test
public void test2(){
Girl girl = new Girl();
// girl = null;
//ofNullable(T t):t可以为null
Optional<Girl> optionalGirl = Optional.ofNullable(girl);
System.out.println(optionalGirl);
//orElse(T t1):如果单前的Optional内部封装的t是非空的,则返回内部的t.
//如果内部的t是空的,则返回orElse()方法中的参数t1.
Girl girl1 = optionalGirl.orElse(new Girl("赵丽颖"));
System.out.println(girl1);

}


public String getGirlName(Boy boy){
return boy.getGirl().getName();
}

@Test
public void test3(){
Boy boy = new Boy();
boy = null;
String girlName = getGirlName(boy);
System.out.println(girlName);

}
//优化以后的getGirlName():
public String getGirlName1(Boy boy){
if(boy != null){
Girl girl = boy.getGirl();
if(girl != null){
return girl.getName();
}
}

return null;

}

@Test
public void test4(){
Boy boy = new Boy();
boy = null;
String girlName = getGirlName1(boy);
System.out.println(girlName);

}

//使用Optional类的getGirlName():
public String getGirlName2(Boy boy){

Optional<Boy> boyOptional = Optional.ofNullable(boy);
//此时的boy1一定非空
Boy boy1 = boyOptional.orElse(new Boy(new Girl("迪丽热巴")));

Girl girl = boy1.getGirl();

Optional<Girl> girlOptional = Optional.ofNullable(girl);
//girl1一定非空
Girl girl1 = girlOptional.orElse(new Girl("古力娜扎"));

return girl1.getName();
}

@Test
public void test5(){
Boy boy = null;
boy = new Boy();
boy = new Boy(new Girl("苍老师"));
String girlName = getGirlName2(boy);
System.out.println(girlName);

}



}