问题
I have a code piece like this:
String[] yetToSortedArray = {"Abc","hello world","nihao?","chilemaNin"};
Arrays.parallelSort(yetToSortedArray, Comparator.comparing(String::length));
for(String str : yetToSortedArray){
System.out.println(str + ", ");
}
My question is here: "String::length" What am I really passing in to Comparator.comparing()? Why there is no parenthesis for String::length()?
I think I am using this : https://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html#comparing-java.util.function.Function-java.util.Comparator-
And it says "Accepts a function that extracts a Comparable sort key from a type T, and returns a Comparator that compares by that sort key."
How dos String::length match this type?
Thanks.
回答1:
String::length is a method reference. Using it is equivalent to
Comparator.comparing(s -> s.length())
So it compares strings by comparing their length.
回答2:
TL;DR: You are passing a method reference
Java 8 introduces lambda syntax to the Java language, this is a small part of that, it allows you to pass a method as a lambda.
So you call the method Comparator.comparing, this requires a "key extractor" function that takes an object from the Collection<T> and returns some object of a type U extends Comparable<? super U>.
The method String.length returns an Integer (when boxed) and an Integer is comparable to another Integer. So the call Comparator.comparing(String::length) returns a Comparator<String> that:
- takes a pair of
String,s1, s2 - calls
l1 = s1.lengthandl2 = s2.length - returns
l1.compareTo(l2)
So, Why there is no parenthesis?
Because you are passing a method reference. This method will be called later on an as yet undefined instance. Notice that length is not static on String so String.length() would not compile.
来源:https://stackoverflow.com/questions/29753525/in-java-use-stringlength-for-comparator-comparing