-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMethodReference.java
35 lines (28 loc) · 984 Bytes
/
MethodReference.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
import java.util.function.Consumer;
import java.util.stream.Stream;
public class MethodReference {
public static class Person {
private final String name;
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
public Boolean compareTo(Person p) {
return p.name.compareTo(name) > 0;
}
}
public static void print(String name) {
System.out.println(name);
}
public static void main(String[] args) {
Person target = new Person("f");
Consumer<String> staticPrint = MethodReference::print;
Stream.of("a", "b", "c", "d")
.map(Person::new) // constructor reference
.filter(target::compareTo) // method reference
.map(Person::getName) // instance method reference
.forEach(staticPrint); // static method reference
}
}