Method references are short hand of lambda expression. It is an easy way to delegate a call to an existing method. The method is referenced by using the class name or the object reference with :: separating the method name
e.g. We can call System.out.println with a below statement:
e.g. We can call System.out.println with a below statement:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
numbers.forEach(System.out::println);
package com.corejava.LambdaExpressions.examples;
//method references are short hand of lambda expressionpublic class MethodReferences {
interface IMovie {
Boolean check(Integer id);
}
private void testMovieStaticMethodRef() {
IMovie movie1 = (i) -> i < 100;// movie id less than 100 are classic movies IMovie movie2 = MethodReferences::isClassic;
System.out.println(movie1.check(100));
System.out.println(movie2.check(99));
}
private void testMovieInstanceMethodRef() {
IMovie movie1 = (id) -> id < 200 && id > 100;
MethodReferences methodReferences = new MethodReferences();
IMovie movie2 = methodReferences::isComedy;
System.out.println(movie1.check(101));
System.out.println(movie2.check(201));
}
public static void main(String[] args) {
MethodReferences methodReferences = new MethodReferences();
methodReferences.testMovieStaticMethodRef();
methodReferences.testMovieInstanceMethodRef();
}
private boolean isComedy(Integer id) {
return id < 200 && id > 100;
}
public static Boolean isClassic(Integer id) {
return id < 100;
}
}
Comments
Post a Comment