【发布时间】:2020-07-19 02:15:17
【问题描述】:
我有两个数组列表
答:5 3 2 6 1 4
B:0 1 2 0 3 2
我想根据 A 中的相应值对 B 进行排序,所以我应该得到:3 2 1 2 0 0
当我使用以下代码时:
ArrayList<Integer> D=new ArrayList<Integer>(B);
Collections.sort(B, Comparator.comparing(s -> A.get(D.indexOf(s))));
或:
ArrayList<Integer> D = new ArrayList<Integer>(B);
Collections.sort(B, new Comparator<Integer>(){
public int compare(Integer a,Integer b){
return Integer.compare(A.get(D.indexOf(a)),A.get(D.indexOf(b)));
}
});
如果 B 中的元素是唯一的,它会起作用,但是由于 2 和 0 都有 2 次出现,所以每次调用 A.get(D.indexOf(2)) 时,都会返回 2 而永远不会返回 4。
所以我终于得到:3 2 2 1 0 0
谁能帮我用一个比较器来处理这个问题?我不想做一个完整的排序算法,但也欢迎这样的解决方案。
【问题讨论】:
-
使用比较器是不可能做到的,因为您在这里尝试做的不是排序。
标签: java sorting arraylist collections comparator