I know in java Collections class, there is a static method sort:
sort(List<T> list, Comparator<? super T> c**)
The second argument in sort should be an object which implements Comparator interface and it's compare method.
But when I learn lambda's method reference, I see this example:
public class Test
{
public static void main(String[] args)
{
new Test().sortWord();
}
public void sortWord()
{
List<String> lst = new ArrayList<>();
lst.add("hello");
lst.add("world");
lst.add("apple");
lst.add("zipcode");
Collections.sort(lst, this::compareWord);
System.out.println(lst);
}
public int compareWord(String a, String b)
{
return a.compareTo(b);
}
}
This is an example of method reference for instance method. the compareWord method has nothing to do with the Comparator interface, I can not understand why this works? can anyone explain this?
Thank you very much.
int compareWord(String a, String b)
has the same signature as the int compare(String o1, String o2)
method of the Comparator<String>
interface. Therefore it can be used as an implementation of that interface.
This is a shorter way of writing:
Collections.sort(lst, new Comparator<String> () {
public int compare (String o1, String o2) {
return compareWord(o1,o2);
}
});
In Java 8 any functional interface such as Comparator
(i.e. interface having a single abstract method) can be implemented with a method reference of a method having a signature matching the signature of that interface's abstract method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With