Java Comparator.comparing not comparing?

前端 未结 4 1102
遥遥无期
遥遥无期 2021-02-19 21:09

Following this question about sorting a list by another list, I tried to do the same thing - but from some reason it doesn\'t work for me. What am I missing?

            


        
相关标签:
4条回答
  • 2021-02-19 21:44

    You are sorting the numbers by their position in the order list, but none of the numbers occur in the order list. In this case, indexOf will return -1 for everything, meaning everything is equal to everything else. In such a case, the resulting sort order is unspecified - though you may realistically assume that it would not change.

    0 讨论(0)
  • 2021-02-19 21:45

    You can make a list of pairs :

    [3.0, 5.0]
    [1.0, 0.9]
    [2.0, 10.4]
    

    Then sort this list of pairs by the first value of each array :

    [1.0, 0.9]
    [2.0, 10.4]
    [3.0, 5.0]
    

    Here is the code :

    List<Double> nums = Arrays.asList(5.0, 0.9, 10.4);
    List<Double> order = Arrays.asList(3.0, 1.0, 2.0);
    
    List<Double[]> pairs = new ArrayList<>();
    for (int i = 0; i < nums.size(); i++) {
        pairs.add(new Double[] {order.get(i), nums.get(i)});
    }
    
    pairs.sort(Comparator.comparing(pair -> pair[0]));
    
    for (Double[] pair : pairs) {
        System.out.print(pair[1] + " ");
    }
    

    Output :

    0.9 10.4 5.0 
    
    0 讨论(0)
  • 2021-02-19 21:46

    The Comparator you are supplying calls indexOf for every num passed. The returned values are -1 on all calls, so the order is preserverd as-is.

    You need to sort natural.

    Sorting by another list of Double should be possible, but unnecessarily complicated, it would be simpler to provide a custom Object which sorts as desired.

    0 讨论(0)
  • 2021-02-19 21:48

    Update

    List<Double> nums = Arrays.asList(5.0, 0.9, 10.4);
    List<Double> order = Arrays.asList(3.0, 1.0, 2.0);
    Map<Double,Double> numToOrder = new HashMap<>();
    for (int i = 0; i < nums.size(); ++i) {
        numToOrder.put(nums.get(i), order.get(i));
    }
    nums.sort(Comparator.comparing(num -> numToOrder.get(num)));
    System.out.println(nums);
    

    Original (wrong) answer

    (nums is modified in place, and the lambda returning key returns wrong results)

    List<Double> nums = Arrays.asList(5.0, 0.9, 10.4);
    List<Double> order = Arrays.asList(3.0, 1.0, 2.0);
    nums.sort(Comparator.comparing(num -> order.get(nums.indexOf(num))));
    System.out.println(nums);
    
    0 讨论(0)
提交回复
热议问题