JDK8的新特性(一)

本文已被阅读过 Posted by Liao Can on 2019-03-02

Lambda表达式

1
2
3
4
5
6
7
8
9
10
//示例:集合排序(函数体只有一行不需大括号)
List<String> strList = Arrays.asList( "d", "a", "b" );
strList.sort( ( e1, e2 ) -> e1.compareTo( e2 ) );
strList.forEach(( String e ) -> System.out.println( e ));

//示例:遍历集合(函数体有多行代码需大括号)
Arrays.asList( "a", "b", "d" ).forEach(( String e ) -> {
System.out.println( e );
System.out.println( e );
} );

方法引用

方法引用

  1. 方法引用所引用的方法的参数列表与返回值类型,需要与函数式接口中抽象方法的参数列表和返回值类型保持一致
  2. 若Lambda 的参数列表的第一个参数,是实例方法的调用者,第二个参数(或无参)是实例方法的参数时,格式: ClassName::MethodName

示例:对象的引用 :: 实例方法名

1
2
3
4
5
6
7
8
9
10
11
12
13
14
//对象的引用 :: 实例方法名
@Test
public void objectTest(){
PrintStream ps = System.out;
Consumer<String> con = (str) -> ps.println(str);
con.accept("Hello World!");

System.out.println("--------------------------------");

Consumer<String> con2 = ps::println;
con2.accept("Hello Java8!");

Consumer<String> con3 = System.out::println;
}

示例:类名 :: 静态方法名

1
2
3
4
5
6
7
8
9
//类名 :: 静态方法名
@Test
public void classTest(){
Comparator<Integer> com = (x, y) -> Integer.compare(x, y);

System.out.println("-------------------------------------");

Comparator<Integer> com2 = Integer::compare;
}

示例:类名 :: 实例方法名

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
public class Employee {

private int id;
private String name;
private int age;
private double salary;

public Employee() {
}

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

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

public Employee(int id, String name, int age, double salary) {
this.id = id;
this.name = name;
this.age = age;
this.salary = 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 String show() {
return "测试方法引用!";
}

@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + id;
result = prime * result + ((name == null) ? 0 : name.hashCode());
long temp;
temp = Double.doubleToLongBits(salary);
result = prime * result + (int) (temp ^ (temp >>> 32));
return result;
}

@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Employee other = (Employee) obj;
if (age != other.age)
return false;
if (id != other.id)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (Double.doubleToLongBits(salary) != Double.doubleToLongBits(other.salary))
return false;
return true;
}

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

}

//类名 :: 实例方法名

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@Test
public void classInstanceTest(){
BiPredicate<String, String> bp = (x, y) -> x.equals(y);
System.out.println(bp.test("abcde", "abcde"));

System.out.println("-----------------------------------------");

BiPredicate<String, String> bp2 = String::equals;
System.out.println(bp2.test("abc", "abc"));

System.out.println("-----------------------------------------");


Function<Employee, String> fun = (e) -> e.show();
System.out.println(fun.apply(new Employee()));

System.out.println("-----------------------------------------");

Function<Employee, String> fun2 = Employee::show;
System.out.println(fun2.apply(new 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
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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
示例:引用无参构造器
public class Employee {

private int id;
private String name;
private int age;
private double salary;

public Employee() {
}

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

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

public Employee(int id, String name, int age, double salary) {
this.id = id;
this.name = name;
this.age = age;
this.salary = 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 String show() {
return "测试方法引用!";
}

@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + id;
result = prime * result + ((name == null) ? 0 : name.hashCode());
long temp;
temp = Double.doubleToLongBits(salary);
result = prime * result + (int) (temp ^ (temp >>> 32));
return result;
}

@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Employee other = (Employee) obj;
if (age != other.age)
return false;
if (id != other.id)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (Double.doubleToLongBits(salary) != Double.doubleToLongBits(other.salary))
return false;
return true;
}

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

}

//构造器引用
@Test
public void defaultConstructorTest(){
Function<String, Employee> fun = Employee::new;

BiFunction<String, Integer, Employee> fun2 = Employee::new;
}

示例:引用有参构造器
public class Employee {

private int id;
private String name;
private int age;
private double salary;

public Employee() {
}

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

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

public Employee(int id, String name, int age, double salary) {
this.id = id;
this.name = name;
this.age = age;
this.salary = 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 String show() {
return "测试方法引用!";
}

@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + id;
result = prime * result + ((name == null) ? 0 : name.hashCode());
long temp;
temp = Double.doubleToLongBits(salary);
result = prime * result + (int) (temp ^ (temp >>> 32));
return result;
}

@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Employee other = (Employee) obj;
if (age != other.age)
return false;
if (id != other.id)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (Double.doubleToLongBits(salary) != Double.doubleToLongBits(other.salary))
return false;
return true;
}

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

}

@Test
public void constructorTest(){
Supplier<Employee> sup = () -> new Employee();
System.out.println(sup.get());

System.out.println("------------------------------------");

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

数组引用

示例:字符串数组引用

1
2
3
4
5
6
7
8
9
10
11
12
13
//数组引用
@Test
public void arrayTest(){
Function<Integer, String[]> fun = (args) -> new String[args];
String[] strs = fun.apply(10);
System.out.println(strs.length);

System.out.println("--------------------------");

Function<Integer, Employee[]> fun2 = Employee[] :: new;
Employee[] emps = fun2.apply(20);
System.out.println(emps.length);
}

函数式接口

示例:消费型接口

1
2
3
4
5
6
7
8
9
//Consumer<T> 消费型接口 :
@Test
public void consumerTest(){
happy(10000, (m) -> System.out.println("每次消费:" + m + "元"));
}

public void happy(double money, Consumer<Double> con){
con.accept(money);
}

示例:供给型接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//Supplier<T> 供给型接口 :
@Test
public void supplierTest(){
List<Integer> numList = getNumList(10, () -> (int)(Math.random() * 100));

for (Integer num : numList) {
System.out.println(num);
}
}

//需求:产生指定个数的整数,并放入集合中
public List<Integer> getNumList(int num, Supplier<Integer> sup){
List<Integer> list = new ArrayList<>();

for (int i = 0; i < num; i++) {
Integer n = sup.get();
list.add(n);
}

return list;
}

示例:函数型接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
//Function<T, R> 函数型接口:
@Test
public void functionTest(){
String newStr = strHandler("\t\t\t 呵呵 ", (str) -> str.trim());
System.out.println(newStr);

String subStr = strHandler("呵呵", (str) -> str.substring(2, 5));
System.out.println(subStr);
}

//需求:用于处理字符串
public String strHandler(String str, Function<String, String> fun){
return fun.apply(str);
}

示例:断言型接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//Predicate<T> 断言型接口:
@Test
public void predicateTest(){
List<String> list = Arrays.asList("Hello", "atguigu", "Lambda", "www", "ok");
List<String> strList = filterStr(list, (s) -> s.length() > 3);

for (String str : strList) {
System.out.println(str);
}
}

//需求:将满足条件的字符串,放入集合中
public List<String> filterStr(List<String> list, Predicate<String> pre){
List<String> strList = new ArrayList<>();

for (String str : list) {
if(pre.test(str)){
strList.add(str);
}
}

return strList;
}

官方文档

https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html
教程 : http://www.runoob.com/java/java8-new-features.html


支付宝打赏 微信打赏

赞赏一下