简体   繁体   English

按第一个元素对字符串数组列表进行排序

[英]Sort List of string arrays by first element

I want to sort a list of string arrays by first element in each array element of same list, in reverse order, so 2, 1, 0我想按相同列表的每个数组元素中的第一个元素以相反的顺序对字符串数组列表进行排序,因此 2, 1, 0

Here's what i tried so far:这是我到目前为止尝试过的:

List<String[]> array = new ArrayList<>();

String[] arr1 = {"0", "1/1"};
String[] arr2 = {"1", "1/2"};
String[] arr3 = {"2", "1/4"};

array.add(arr1);
array.add(arr2);
array.add(arr3);

Comparator<String[]> byFirstElement = 
    (String[] array1, String[] array2) -> Integer.parseInt(array1[0]) - 
                                           Integer.parseInt(array2[0]);


List<String[]> result = array.stream()
        .sorted(array,byFirstElement) // error here
        .collect(Collectors.toList());

The problem is that at sorted line i have an error highlighted, saying: "sorted(java.util.List, java.util.Comparator问题是在排序行我有一个错误突出显示,说:“排序(java.util.List,java.util.Comparator

Stream.sorted() takes a comparator (in addition to the overload that takes no argument). Stream.sorted()需要一个比较器(除了不带参数的重载)。 So all you need is ...sorted(byFirstElement)... (the stream sorts its elements)所以你只需要...sorted(byFirstElement)... (流对其元素进行排序)

Note that your comparison logic won't sort in descending order, so you either need to change it to请注意,您的比较逻辑不会按降序排序,因此您需要将其更改为

Comparator<String[]> byFirstElement = 
    (array1, array2) -> Integer.parseInt(array2[0]) - Integer.parseInt(array1[0]);
                        //reversed

or reverse it when calling sorted() :或在调用sorted()时反转它:

....sorted(byFirstElement.reversed())

You can simplify your code with the Comparator.comparing method as follows:您可以使用Comparator.comparing方法简化代码,如下所示:

List<String[]> list = List.of(
        new String[]{"0", "1/1"},
        new String[]{"1", "1/2"},
        new String[]{"2", "1/4"});

List<String[]> sorted = list.stream()
        .sorted(Comparator.comparing(
                arr -> Integer.parseInt(arr[0]), Comparator.reverseOrder()))
        .collect(Collectors.toList());

// output
sorted.stream().map(Arrays::toString).forEach(System.out::println);

Output:输出:

[2, 1/4]
[1, 1/2]
[0, 1/1]

See also:也可以看看:
How to sort by a field of class with its own comparator? 如何使用自己的比较器按类的字段排序?
Sorting 2D array of strings in alphabetical order 按字母顺序对二维字符串数组进行排序

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM