-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMethodReferencesAndLambda.java
More file actions
85 lines (71 loc) · 3.21 KB
/
MethodReferencesAndLambda.java
File metadata and controls
85 lines (71 loc) · 3.21 KB
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
package chapter7.lambdas;
import java.time.Instant;
import java.util.function.IntFunction;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.function.ToIntFunction;
import java.util.function.UnaryOperator;
import static java.time.temporal.ChronoUnit.SECONDS;
/**
* 主要介绍5中方法引用,以及与它们等效的λ表达式实现<br>
* <pre>
* 静态方法引用: {@link #staticEg()}
* 绑定引用: {@link #boundEg()}
* 未绑定引用: {@link #unboundEg()}
* 构造函数引用: {@link #constructorEg()}
* 数组构造函数引用: {@link #arrayConstructorEg()}
* </pre>
*/
public class MethodReferencesAndLambda {
public static void main(String[] args) {
staticEg();
boundEg();
unboundEg();
constructorEg();
arrayConstructorEg();
}
/**
* 静态方法引用
*/
static void staticEg() {
// 标准函数ToIntFunction<T> 替代Function<String,Integer> ,优先使用基本类型原则: 不要尝试使用带有包装类的基本函数式接口,而不是使用基本类型函数式接口
ToIntFunction<String> references = Integer::parseInt; // 方法引用
ToIntFunction<String> lambda = str -> Integer.parseInt(str); // λ表达式
System.out.println(references.applyAsInt("124"));
System.out.println(lambda.applyAsInt("124"));
}
/**
* 绑定引用在本质上与静态引用相似:函数对象接受与引用方法相同的参数
*/
static void boundEg() {
Predicate<Instant> references = Instant.now()::isAfter; // 方法引用
Predicate<Instant> lambda = ins -> Instant.now().isAfter(ins); // λ表达式
System.out.println(references.test(Instant.now().plus(1L, SECONDS)));
System.out.println(lambda.test(Instant.now().plus(1L, SECONDS)));
}
/**
* 未绑定引用中,在应用函数对象时通过方法声明参数之前的附加参数指定接收对象
*/
static void unboundEg() {
// 使用标准函数UnaryOperator<T> 替代Function
UnaryOperator<String> references = String::toLowerCase; // 方法引用
UnaryOperator<String> lambda = str -> str.toLowerCase(); // λ表达式
System.out.println(references.apply("ABC"));
System.out.println(lambda.apply("ABC"));
}
/**
* 构造函数引用用作工厂对象
*/
static void constructorEg() {
Supplier<MethodReferencesAndLambda> references = MethodReferencesAndLambda::new; // 方法引用
Supplier<MethodReferencesAndLambda> lambda = () -> new MethodReferencesAndLambda(); // λ表达式
System.out.println(references.get().getClass());
System.out.println(lambda.get().getClass());
}
static void arrayConstructorEg() {
IntFunction<MethodReferencesAndLambda[]> references = MethodReferencesAndLambda[]::new; // 方法引用
IntFunction<MethodReferencesAndLambda[]> lambda = len -> new MethodReferencesAndLambda[len]; // λ表达式
System.out.println(references.apply(2).length);
System.out.println(lambda.apply(2).length);
}
}