我希望使用months
方法按长度对数组Arrays.sort
中的String元素进行排序。我被告知here,可以使用lambda表达式而不是创建实现Comparator的新类。是否完全相同,但它不起作用。
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
}
}
答案 0 :(得分:50)
最干净的方式是:
Arrays.sort(months, Comparator.comparingInt(String::length));
或者,使用静态导入:
Arrays.sort(months, comparingInt(String::length));
然而,这也会起作用,但更详细:
Arrays.sort(months,
(String a, String b) -> a.length() - b.length());
或更短:
Arrays.sort(months, (a, b) -> a.length() - b.length());
最后你的最后一个:
Arrays.sort(months,
(String a, String b) -> { return Integer.signum(a.length() - b.length()) };
);
;
放错地方了 - 应该是:
Arrays.sort(months,
(String a, String b) -> { return Integer.signum(a.length() - b.length()); }
);
答案 1 :(得分:1)
您正在寻找:
Arrays.sort(months, (a, b) -> Integer.signum(a.length() - b.length()));
答案 2 :(得分:1)
您正在寻找的功能是Java 8,尚未发布。它计划在几个月内发布,如果你想等待,或者如果没有beta下载可用。