在 Java 8 中使用 Lambda 对 ArrayList 进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23701943/
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
Sorting ArrayList with Lambda in Java 8
提问by Jeef
Could somebody show me a quick example how to sort an ArrayList
alphabetically in Java 8 using the new lambda syntax.
有人可以向我展示一个快速示例,如何ArrayList
使用新的 lambda 语法在 Java 8 中按字母顺序排序。
采纳答案by poosliver
For strings this would work
对于字符串,这将起作用
arrayList.sort((p1, p2) -> p1.compareTo(p2));
回答by Louis Wasserman
Are you just sorting String
s? If so, you don't need lambdas; there's no point. You just do
你只是排序String
s吗?如果是这样,您就不需要 lambdas;毫无意义。你只要做
import static java.util.Comparator.*;
list.sort(naturalOrder());
...though if you're sorting objects with a String
field, then it makes somewhat more sense:
...虽然如果你用一个String
字段对对象进行排序,那么它更有意义:
list.sort(comparing(Foo::getString));
回答by Dmitry Ginzburg
In functional programming, you're not using the old objects to operate on them, but creating the new one in such a fashion:
在函数式编程中,您不是使用旧对象对它们进行操作,而是以这种方式创建新对象:
list.stream().sorted().map(blah-blah).filter(...)...
回答by UTF_or_Death
Use list.sort(String::compareToIgnoreCase)
用 list.sort(String::compareToIgnoreCase)
Using list.sort(String::compareTo)
or list.sort(Comparator.naturalOrder())
will give incorrect (ie. non-alphabetical) results. It will sort anyupper case letter before alllower case letters, so the array ["aAAA","Zzz", "zzz"]
gets sorted to ["Zzz", "aAAA", "zzz"]
使用list.sort(String::compareTo)
orlist.sort(Comparator.naturalOrder())
会给出不正确的(即非字母顺序的)结果。它将在所有小写字母之前对任何大写字母进行排序,因此数组被排序为["aAAA","Zzz", "zzz"]
["Zzz", "aAAA", "zzz"]
回答by Sai prateek
Suppose you have List of names(String) which you want to sort alphabetically.
假设您有要按字母顺序排序的名称列表(字符串)。
List<String> result = names.stream().sorted(
Comparator.comparing(n->n.toString())).collect(Collectors.toList());
its working perfectly.
它的工作完美。
回答by Chris311
A really generic solution would be to introduce some StreamUtil
like
一个真正通用的解决方案是引入一些StreamUtil
像
public class StreamUtil {
private StreamUtil() {
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public static <TYPE> Comparator<TYPE> sort(Function<TYPE, ? extends Comparable> getterFunction, boolean descending) {
if (descending) {
return (o1, o2) -> getterFunction.apply(o2).compareTo(getterFunction.apply(o1));
}
return (o1, o2) -> getterFunction.apply(o1).compareTo(getterFunction.apply(o2));
}
}
The call would look something like
电话看起来像
list.stream().sorted(sort(YourClass::getSortProperty, true));
回答by Faraz
Most concise:
最简洁:
Collections.sort(stringList, String::compareToIgnoreCase);
回答by Ithar
If you have an array with elements that have natural ordering (i.e String
, int
, double
); then it can be achieved by:
如果您有一个包含自然排序元素的数组(即String
, int
, double
);那么它可以通过以下方式实现:
List<String> myList = new ArrayList<>();
myList.add("A");
myList.add("D");
myList.add("C");
myList.add("B");
myList.sort(Comparator.comparing(s -> s));
myList.forEach(System.out::println);
If on the another hand you have an array of objects and you want to sort base on some sort of object field, then you can use:
另一方面,如果您有一个对象数组并且您想根据某种对象字段进行排序,那么您可以使用:
class User {
double score;
// Constructor // Getters // Setters
}
List<User> users = new ArrayList<>();
users.add(new User(19d));
users.add(new User(67d));
users.add(new User(50d));
users.add(new User(91d));
List<User> sortedUsers = users
.stream()
.sorted(Comparator.comparing(User::getScore))
.collect(Collectors.toList());
sortedUsers.forEach(System.out::println);
If the sorting is more complex, then you would have to write your own comparator and pass that in.
如果排序更复杂,那么您必须编写自己的比较器并将其传入。
回答by lafleur
List<Product> list = new ArrayList<>();
List<String> list1 = new ArrayList<>();
list.add(new Product(1));
list.add(new Product(2));
list.add(new Product(3));
list.add(new Product(10));
Collections.sort(list, Comparator.comparing((Product p) -> p.id));
for (Product p : list) {
System.out.println(p.id);
}
回答by ZhekaKozlov
Lambdas shouldn't be the goal. In your case, you can sort it the same way as in Java 1.2:
Lambda 不应该是目标。在您的情况下,您可以按照与 Java 1.2 中相同的方式对其进行排序:
Collections.sort(list); // case sensitive
Collections.sort(list, String.CASE_INSENSITIVE_ORDER); // case insensitive
If you want to do it in Java 8 way:
如果你想用 Java 8 的方式来做:
list.sort(Comparator.naturalOrder()); // case sensitive
list.sort(String.CASE_INSENSITIVE_ORDER); // case insensitive
You can also use list.sort(null)
but I don't recommend this because it's not type-safe.
您也可以使用,list.sort(null)
但我不推荐这样做,因为它不是类型安全的。