|
|
Method Reference - Reference to a Static Method example.
This example shows how to call static methods using Method Reference feature. It is pretty simple and basic example.
package com.java2novice.methodreference;
import java.util.ArrayList;
import java.util.List;
public class StaticMethodReferenceEx {
public static void main(String a[]) {
List<String> countryList = new ArrayList<>();
countryList.add("India");
countryList.add("USA");
countryList.add("Japan");
countryList.add("Canada");
// print the list elements in normal way
System.out.println("<--- Prior to java-8 --->");
for(String str:countryList) {
StaticMethodReferenceEx.printString(str);
}
// In Method Reference way
System.out.println("\n<--- java-8 method reference way --->");
countryList.forEach(StaticMethodReferenceEx::printString);
// in Lambda expression way
System.out.println("\n<--- java-8 lambda expression way --->");
countryList.forEach(str -> StaticMethodReferenceEx.printString(str));
}
public static void printString(String str) {
System.out.println(str);
}
}
|
|
Output: |
<--- Prior to java-8 --->
India
USA
Japan
Canada
<--- java-8 method reference way --->
India
USA
Japan
Canada
<--- java-8 lambda expression way --->
India
USA
Japan
Canada
|
|
|
|
|
Java-8 Method References Examples
- Method Reference - Reference to a Static Method example.
- Method Reference - Reference to a Instance Method example.
- Method Reference - Reference to a Constructor example.
|
|
Difference between super() and this()
super() is used to call super class constructor, whereas this() used to call
constructors in the same class, means to call parameterized constructors.
When I do good, I feel good; when I do bad, I feel bad, and that is my religion.
-- Abraham Lincoln
|