java:带有 lambda 表达式的 Arrays.sort()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21970719/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
java: Arrays.sort() with lambda expression
提问by matt-pielat
I want to sort String elements in the array months
by length using Arrays.sort
method. I was told here, that it's possible to use lambda expressions instead of creating new class implementing Comparator. Did it exactly the same way, yet it doesn't work.
我想months
使用Arrays.sort
方法按长度对数组中的字符串元素进行排序。有人告诉我,在这里,它是可以使用的,而不是创建新类实现比较lambda表达式。以完全相同的方式做了,但它不起作用。
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
}
}
采纳答案by assylias
The cleanest way would be:
最干净的方法是:
Arrays.sort(months, Comparator.comparingInt(String::length));
or, with a static import:
或者,使用静态导入:
Arrays.sort(months, comparingInt(String::length));
However, this would work too but is more verbose:
但是,这也可以工作,但更冗长:
Arrays.sort(months,
(String a, String b) -> a.length() - b.length());
Or shorter:
或更短:
Arrays.sort(months, (a, b) -> a.length() - b.length());
Finally your last one:
最后你的最后一个:
Arrays.sort(months,
(String a, String b) -> { return Integer.signum(a.length() - b.length()) };
);
has the ;
misplaced - it should be:
有;
错位的-它应该是:
Arrays.sort(months,
(String a, String b) -> { return Integer.signum(a.length() - b.length()); }
);
回答by Josh M
You're looking for this:
你正在寻找这个:
Arrays.sort(months, (a, b) -> Integer.signum(a.length() - b.length()));
回答by Tim B
The functionality you are looking for is in Java 8, which has not yet been released. It is scheduled for release in a few months if you want to wait, or if not beta downloads are available.
您正在寻找的功能在尚未发布的 Java 8 中。如果您想等待,或者没有测试版下载,它计划在几个月内发布。