logo

Method References


Show

Method references help to tip to the method by their names. a way reference is described using the "::" symbol. a way reference are often wont to point the subsequent kind of methods −

  • Static approach
  • Instance approach
  • Constructors using new operator (TreeSet::new)

Different types of Method Reference Example

Create the subsequent Java program using any editor of your choice in, say, C:\> JAVA

Java8Tester.java
import java.util.List;
import java.util.ArrayList;

public class Java8Tester {

   public static void main(String args[]) {
      List names = new ArrayList();
      names.add("Mahesh");
      names.add("Suresh");
      names.add("Ramesh");
      names.add("Naresh");
      names.add("Kalpesh");
      names.forEach(System.out::println);
   }
}

Above we have used the system out::printIn method as a static approach reference

Confirm You Result:

Assemble the class using the javac compiler as follows:

C:\JAVA>javac Java8Tester.java

Now, you have to Run Java8Tester as given below:

C:\JAVA>java Java8Tester

You must get the output as follows:

Mahesh
Suresh
Ramesh
Naresh
Kalpesh