forked from Rapter1990/JavaStreamAPIExamples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMethodReferenceExample.java
More file actions
51 lines (34 loc) · 1.66 KB
/
MethodReferenceExample.java
File metadata and controls
51 lines (34 loc) · 1.66 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
package functionalexamples;
import java.util.Arrays;
import java.util.List;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.ToIntFunction;
public class MethodReferenceExample {
public static void main(String[] args) {
methodReferenceInstanceMethodViaObject();
methodReferenceInstanceMethodViaClass();
}
private static void methodReferenceInstanceMethodViaClass() {
System.out.println("Method reference to instance method of arbitary type");
String input = "Lambdas";
//1.Length of string
ToIntFunction<String> lengthLambdas = (String s) -> s.length();
ToIntFunction<String> lengthMethodReference = String::length;
System.out.println("Length of string using Lambda: "+lengthLambdas.applyAsInt(input));
System.out.println("Length of string using MR: "+lengthMethodReference.applyAsInt(input));
// 2.Find substring
BiFunction<String, Integer, String> substringLambdas = (text, position) -> text.substring(position);
BiFunction<String, Integer, String> substringMethodReference = String::substring;
System.out.println("Substring using Lambdas : "+substringLambdas.apply(input, 3));
System.out.println("Substring using MR : "+substringMethodReference.apply(input, 3));
}
private static void methodReferenceInstanceMethodViaObject() {
//1.
Consumer<String> printLambda = (s) -> System.out.println(s);
Consumer<String> printMR = System.out::println;
//2.
List<String> list = Arrays.asList("a","b","c","d","e");
list.forEach(System.out::println);
}
}