-
Notifications
You must be signed in to change notification settings - Fork 2
/
FunctionReference.java
122 lines (97 loc) · 2.89 KB
/
FunctionReference.java
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
package com.diyishuai.java8.function;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.ArrayList;
import java.util.List;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Supplier;
/**
* @author Shea
* @date 2021-01-21
* @description
*/
public class FunctionReference {
public static void main(String[] args) {
classConstructorFunctionReference();
classStaticFunctionReference();
instanceFunctionReference();
}
/**
* 类构造方法引用
*/
private static void classConstructorFunctionReference() {
System.out.println("类构造方法引用:");
//构造引用
// 0 无参构造
Supplier<Apple> appleSupplier = Apple::new;
Apple a0 = appleSupplier.get();
System.out.println(a0);
// 1 单参构造
Function<String, Apple> appleFunction = Apple::new;
Apple a1 = appleFunction.apply("1");
System.out.println(a1);
// 2 双参构造
BiFunction<String, Double, Apple> appleBiFunction = Apple::new;
Apple a2 = appleBiFunction.apply("2", 0.5);
System.out.println(a2);
}
/**
* 类静态方法引用
*/
private static void classStaticFunctionReference() {
System.out.println("类静态方法引用");
List list = new ArrayList();
list.add(new Apple("1"));
list.add(new Apple("2"));
list.add(new Apple("3"));
list.add(new Apple[]{new Apple("4"), new Apple("5")});
list.stream().forEach(Show::show);
}
/**
* 实例方法引用
*/
private static void instanceFunctionReference() {
System.out.println("实例方法引用");
List<Apple> list = new ArrayList();
list.add(new Apple("1"));
list.add(new Apple("2"));
list.add(new Apple("3"));
list.stream().map(a -> a.getId()).forEach(System.out::println);
System.out.println("----");
list.stream().map(Apple::getId).forEach(System.out::println);
}
}
@Data
@AllArgsConstructor
@NoArgsConstructor
class Apple {
private String id;
private double weight;
private String color;
public Apple(String id) {
this.id = id;
}
public Apple(String id, double weight) {
this.id = id;
this.weight = weight;
}
}
class Show {
public static void show(Object obj) {
if (obj instanceof List) {
for (Object o : (List) obj) {
System.out.print(o.toString() + "\t");
}
System.out.println();
} else if (obj instanceof Object[]) {
for (Object o : (Object[]) obj) {
System.out.print(o.toString() + "\t");
}
System.out.println();
} else {
System.out.println(obj.toString());
}
}
}