-
Notifications
You must be signed in to change notification settings - Fork 54
/
Copy pathMethodReferences.java
152 lines (50 loc) · 2 KB
/
MethodReferences.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
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
package streams;
import java.util.Comparator;
import java.util.function.*;
public class MethodReferences {
interface ThreadSupplier {
Thread giveMeAThread();
}
@SuppressWarnings("unused")
public static void main(String[] args) {
// Static method
Supplier<Thread> s1 = Thread::currentThread;
// Nothing special about 'Supplier'...
ThreadSupplier ts = Thread::currentThread;
// Instance method (instance specified)
Employee frank = new Employee("Frank", 3000);
Integer i = frank.getSalary();
Supplier<Integer> s2 = frank::getSalary;
System.out.println(s2.get());
// A common instance method (instance specified)
Consumer<String> c1 = System.out::println;
// An instance method (instance not specified)
Function<Employee,Integer> f1 = Employee::getSalary;
Integer frankSalary = f1.apply(frank);
// A useful application: building a comparator based on a field
// comparing expects Function<Employee, U>,
// where U supports natural ordering (i.e., Comparable)
Comparator<Employee> byName =
Comparator.comparing(Employee::getName);
main2();
}
public static <T> void printAll(T[] array,
Function<T,String> toStringFun) {
int i = 0;
for (T t: array)
System.out.println(i++ + ":\t" + toStringFun.apply(t));
}
public static void main2() {
Employee dept[] = new Employee[5];
dept[0] = new Employee("Alec", 1500);
dept[1] = new Employee("Bob", 1600);
dept[2] = new Employee("Claire", 1700);
dept[3] = new Employee("Danielle", 1800);
dept[4] = new Employee("Ethan", 1900);
printAll(dept, Employee::getName);
System.out.println("");
// Compile-time error: type inference failure
// printAll(dept, Employee::getSalary);
printAll(dept, emp -> "" + emp.getSalary());
}
}