This time we are studying method reference. It seems that you can assign a method to a variable of functional IF. I think it's an image that says to execute this assignment (specified) method when the (only) abstract method of functional IF is called. For those who have forgotten the functional IF see previous article
For the time being, prepare two functional IFs as shown below.
@FunctionalInterface
public interface SampleFunctionalIF {
String methodA();
}
@FunctionalInterface
public interface SampleFunctionalIF2 {
String methodA(String A, String B);
}
So, here is a class that calls these
/**
*Study method reference.
*You can assign a method to a variable of functional IF.
*Functional IF(I think it's an image of telling you to execute this assignment (specified) method when the (only) abstract method is called.
* @author komikcomik
*
*/
public class MethodRef {
public static void main(String[] args) {
/*With no arguments*/
//An image that asks you to execute the method hello of this class instead when methodA, which is an abstract IF of SampleFunctionalIF, is called.
System.out.println("-----Example 1-----");
SampleFunctionalIF if1 = MethodRef::hello;
System.out.println(if1.methodA());
/*With one argument*/
//This area is just priced appropriately in the list
System.out.println("-----Example 2-----");
List<String> l = new ArrayList<>();
l.add("hoge");
l.add("hogehoge");
l.forEach(System.out::println); //System implementation of abstract method of List which is functional IF.out.println(s)Image specified as
l.forEach(MethodRef::echo); //It's similar to the one above, but of course you can substitute your own method
/*With 2 arguments*/
System.out.println("-----Example 3-----");
SampleFunctionalIF2 if2 = MethodRef::join;
System.out.println(if2.methodA("Hello", "World"));
}
public static String hello() {
System.out.println("The hello method was called");
return "hello";
}
public static String join(String A, String B) {
return A + B;
}
public static void echo(String s) {
System.out.println(s);
}
}
The execution result is as follows.
-----Example 1-----
The hello method was called
hello
-----Example 2-----
hoge
hogehoge
hoge
hogehoge
-----Example 3-----
HelloWorld
Well as expected. However, I'm not used to writing lambda expressions or writing like :: this time, so I somehow get ready. The lambda expression is written as argument-> processing </ b>, and if you write the equivalent of this example 2 in the lambda expression
l.forEach(s -> {
System.out.println(s);
});
So it seems that a similar effect can be obtained. How do people who use it properly use it properly?
Recommended Posts