- Reference to constructor (1)
- Reference to Static method (2)
- Reference to Instance Method of particular object (3)
Note : The color codes refers with numbers are used in the comments. to make notes clear
I would not say this program is self explanatory. Comments are provided in the major three lines.
Explanation goes here,
Reference to Instance Method of particular object (3)
The "MyComparator" class have override method and instance method too. Collection sort functionality expect compactor object to process the provided list input. So, Created "MyComparator" class instance and supplied to the sort functionality.
Reference to Static method (2)
As like instance method we can call the static methods in the reference. "doPrint" also has the static method reference. This method contain collection forEach also time being skip this content now. It will be covered in later posts.
Reference to constructor (1)
Constructor also calling in the lambda expression way. In case of multiple constructor available, the smarty will recognize by the suitable parameter.
Hint : Try to execute the below code, play with it, change something. then you will surely understand the concept. Method reference major concept are covered in a single program. It is useful for reference while doing other task.
----------------------------------------------- Java 8------------------------------------------------------------------import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class ComparatorMethodReference {
List<String> l;
public ComparatorMethodReference(List<String> l) {
this.l=l;
}
public static void main(String[] args) {
List<String> l = new ArrayList<String>();
l.add("Banana");
l.add("Apple");
l.add("Mango");
Func fun=ComparatorMethodReference::new; // (1) Reference by constructor
ComparatorMethodReference comp=fun.loadList(l);
comp.doJava8Sort();
}
public static void doPrint(List<String> l) {
l.forEach(System.out::println); // (2) Reference to Static method
System.out.println(); // For Empty line
}
public void doJava8Sort() {
MyComparator comparator=new MyComparator();
Collections.sort(l,comparator);
doPrint(l);
Collections.sort(l,comparator::myReverse); // (3) Reference to Instance Method of particular object
doPrint(l);
}
}
class MyComparator implements Comparator<String> {
@Override
public int compare(String st1, String st2) {
return st1.compareTo(st2);
}
public int myReverse(String st1,String st2)
{
return st2.compareTo(st1);
}
}
@FunctionalInterface
interface Func {
ComparatorMethodReference loadList(List<String> l);
}
No comments:
Post a Comment