在Java中,当元素重复时,如何基于另一个数组对一个数组排序?

问题描述 投票:0回答:1

我有两个ArrayLists

A: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
1个回答
1
投票

一种简单的方法如下:

© www.soinside.com 2019 - 2024. All rights reserved.