[英]Sorting List of Arrays by different elements using Java 8 lambdas
如果我有一个List<String[]>
,其中每个String[]
如下所示:{FirstName,LastName,Income,City}我将如何使用Java 8 lambdas按列表对某个值进行排序,例如收入或名字?
Here's a couple examples. 这是几个例子。 Replace x in the first two examples below with the index of the field you'd like to use for sorting. 将前面两个示例中的x替换为您要用于排序的字段的索引。
Collections.sort(personList, (p1, p2) -> p1[x].compareTo(p2[x]));
or 要么
personList.sort((p1, p2) -> p1[x].compareTo(p2[x]);
Also, I agree with @Robin Topper's comment. 另外,我同意@Robin Topper的评论。 If lambdas are required (and you wanted to sort by first name), you could use: 如果需要lambda (并且你想按名字排序),你可以使用:
Collections.sort(personList, (p1, p2) -> p1.getFirstName().compareTo(p2.getFirstName()));
or 要么
personList.sort((p1, p2) -> p1.getFirstName().compareTo(p2.getFirstName()));
Also consider using the comparable implementation from Robin's comment and a data-structure allowing sorting. 还要考虑使用Robin评论中的可比较实现和允许排序的数据结构。
If you can rely on the order in this array, then as simple as: 如果你可以依赖这个数组中的顺序,那么就像这样简单:
List<String[]> list = Arrays.asList(new String[] { "eugene", "test", "300", "LA" },
new String[] { "hunter", "test2", "25", "CA" });
List<String[]> sorted = list.stream()
.sorted(Comparator.comparingLong(s -> Long.parseLong(s[2])))
.collect(Collectors.toList());
sorted.forEach(s -> System.out.println(Arrays.toString(s)));
But the general advice to create an Object
from those fields is much better. 但是从这些字段创建Object
的一般建议要好得多。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.