Java Comparator.comparing not comparing?

前端 未结 4 1028
遥遥无期
遥遥无期 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: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 nums = Arrays.asList(5.0, 0.9, 10.4);
    List order = Arrays.asList(3.0, 1.0, 2.0);
    
    List 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 
    

提交回复
热议问题