【问题标题】:Sort List of string arrays by first element按第一个元素排序字符串数组列表
【发布时间】:2020-01-27 14:29:04
【问题描述】:

我想按相同列表的每个数组元素中的第一个元素对字符串数组列表进行排序,以相反的顺序,所以 2、1、0

到目前为止,这是我尝试过的:

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());

问题是在排序行我有一个错误突出显示,说: “排序(java.util.List,java.util.Comparator

【问题讨论】:

  • 应该是.sorted(byFirstElement)。删除array 参数。

标签: java sorting comparator


【解决方案1】:

Stream.sorted() 带有一个比较器(除了不带参数的重载)。所以你只需要...sorted(byFirstElement)...(流对其元素进行排序)

请注意,您的比较逻辑不会按降序排序,因此您需要将其更改为

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

或调用sorted()时反转:

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

【讨论】:

    【解决方案2】:

    您可以使用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);
    

    输出:

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

    另见:
    How to sort by a field of class with its own comparator?
    Sorting 2D array of strings in alphabetical order

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-01-17
      • 2018-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-23
      • 1970-01-01
      相关资源
      最近更新 更多