Why did this lambda function work?
String[] months = {"January","February","March","April","May","June","July","August","September","October","December"};
Arrays.sort(months,(String a, String b) -> a.length() - b.length());
Why it's a.length() - b.length()
, not just based on a.length()? Why does Arrays.sort(months,(String a) -> a.length())
not work?;
The (String a, String b) -> a.length() - b.length()
is the Single-Abstract-Method shortcut for Comparator
, and Comparator
's compare
method must satisfy compare(a, b) > 0
if and only if compare(b, a) < 0
, otherwise it wouldn't define a proper comparison function. Such a function obviously cannot work if you discarded the argument b
and returned an int
based only on a
. If you wanted to "sort-by" length, you could use Comparator.comparing(String::length)
(see here ).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.