I only knew how to use forEach using a lambda expression, but there was also a method using the method reference "::", so make a note.
Class name (instance) :: method name
You can refer to the method by writing as
list.forEach(System.out :: println);
list.forEach(x -> System.out.println(x));
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
Main main = new Main();
System.out.println("----No1----");
main.test().forEach(main :: myPrint);
System.out.println("----No2----");
main.test().forEach(x -> main.myPrint(x));
}
public List<String> test(){
List<String> list = new ArrayList<>();
list.add("AA");
list.add("BB");
list.add("CC");
list.add("DD");
return list;
}
public void myPrint(String str){
System.out.println(str);
}
}
This is an example of calling the method of the instance, but the execution result is the same for both.
----No1----
AA
BB
CC
DD
----No2----
AA
BB
CC
DD
Recommended Posts