java:具有lambda表达式的Arrays.sort()
我想months
使用Arrays.sort
方法按长度对数组中的字符串元素进行排序。我在这里被告知,可以使用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
}
}
回答:
最干净的方法是:
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()); }
);
以上是 java:具有lambda表达式的Arrays.sort() 的全部内容, 来源链接: utcz.com/qa/434659.html