Java 8 confusion - > String::compareToIgnoreCase

Abdul Mohsin :

Can someone please help me in understanding below :

// This works fine
List list= Arrays.asList("a","b","A","B"); 
str.sort(String::compareToIgnoreCase); 

Can I assign the above method reference to any variable ?

??? holder = String::compareToIgnoreCase;

however I can assign the object reference without any issues like :

String aa = "aa"; 
Function compareFunction = aa::compareToIgnoreCase;

Thanks in advance, Abdul

Ruslan :

String::compareToIgnoreCase is equal to anonymous class:

new Comparator<String>() {
    @Override
    public int compare(String s, String str) {
        return s.compareToIgnoreCase(str);
    }
};

Therefore it can be assigned to variable with type Comparator<String> :

Comparator<String> compareToIgnoreCase = String::compareToIgnoreCase;

At the same time the expression aa::compareToIgnoreCase; means the function with string parameter aa that return Integer.

new Function<String, Integer>() {
    @Override
    public Integer apply(String str) {
        return aa.compareToIgnoreCase(str);
    }
};

Or:

Function<String, Integer> fun = aa::compareToIgnoreCase;

The difference between String::compareToIgnoreCase; and aa::compareToIgnoreCase; is that in the first case we need 2 parameters: string on which method compareToIgnoreCase will be invoked, and string that will passed in this method. It perfectly match the signature of int compare(T o1, T o2);.

In the second case you alredy have one parameter (aa). So you need just one, that will be passed into compareToIgnoreCase. It exactly match R apply(T t);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=90096&siteId=1