Java Comparator.comparing not comparing?

前端 未结 4 1110
遥遥无期
遥遥无期 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:48

    Update

    List nums = Arrays.asList(5.0, 0.9, 10.4);
    List order = Arrays.asList(3.0, 1.0, 2.0);
    Map 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 nums = Arrays.asList(5.0, 0.9, 10.4);
    List order = Arrays.asList(3.0, 1.0, 2.0);
    nums.sort(Comparator.comparing(num -> order.get(nums.indexOf(num))));
    System.out.println(nums);
    

提交回复
热议问题