java: Arrays.sort() with lambda expression
我想使用方法按长度对数组中的字符串元素进行排序。我在这里被告知,可以使用lambda表达式,而不是创建新的类来实现比较器。它以完全相同的方式做了,但它不起作用。months
Arrays.sort
import java.util.Arrays;
import java.util.Comparator;
public class MainClass {
public static void main(String[] args)
{
String[] months = {"January","February","March","April","May","June","July","August","September","October","December"};
System.out.println(Arrays.toString(months)); //printing before
//neither this works:
Arrays.sort(months,
(a, b) -> Integer.signum(a.length() - b.length())
);
//nor this:
Arrays.sort(months,
(String a, String b) -> { return Integer.signum(a.length() - b.length()) };
);
System.out.println(Arrays.toString(months)); //printing after
}
}