Reputation: 135
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
Upvotes: 3
Views: 1396
Reputation: 1
public class Test {
public static void main(String args[]) {
String str1 = "Strings are immutable";
String str2 = "Strings are immutable";
String str3 = "Integers are not immutable";
int result = str1.compareToIgnoreCase( str2 );
System.out.println(result);
result = str2.compareToIgnoreCase( str3 );
System.out.println(result);
result = str3.compareToIgnoreCase( str1 );
System.out.println(result);
} }
Upvotes: 0
Reputation: 6300
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);
Upvotes: 5