Collections.sort 没有给出预期的

时间:2021-03-15 18:25:30

标签: java sorting

我正在尝试根据该索引处的值对数组的索引进行排序。例如。 [0,2,2,1] 将给出 [0,2,3,1] 或 [0,3,2,1]

List<Integer> index_map = new LinkedList(Arrays.asList(0,1,2,3));
final int[] sizes = {0,2,1,1};

Collections.sort(index_map, new Comparator<Integer>() {
    @Override
    public int compare(Integer a, Integer b) {
        return sizes[a] < sizes[b] ? -1 : 1;
    }
});
System.out.println(Arrays.toString(sizes));
System.out.println(index_map);

然而,使用 Collections.sort() 和定义的比较器给出 [0,3,1,2] 代替。有人能告诉我为什么输出是这样的,是否有更好的方法来实现目标?谢谢

1 个答案:

答案 0 :(得分:4)

修正:你错过了等值的情况并且不重新实现比较代码,直接使用方法Integer.compare

List<Integer> index_map = new LinkedList(Arrays.asList(0,1,2,3));
final int[] sizes = {0,2,1,1};

Collections.sort(index_map, new Comparator<Integer>() {
    @Override
    public int compare(Integer a, Integer b) {
        return Integer.compare(sizes[a],sizes[b]);
    }
});

改进:它可以用它的 lambda 版本来减少

Collections.sort(index_map, (a, b) -> Integer.compare(sizes[a], sizes[b]));

Best: 使用comparingInt 允许只指定用于比较的值,也可以直接调用列表中的sort :

index_map.sort(Comparator.comparingInt(a -> sizes[a]));
相关问题