【问题标题】:How to sort one array based on another, when elements repeat, in Java?java - 当元素重复时,如何根据另一个数组对一个数组进行排序?
【发布时间】: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


【解决方案1】:

一个简单的方法如下:

import java.util.ArrayList;
import java.util.List;

public class Main {

    public static void main(String[] args) {
        List<Integer> list1 = List.of(5, 3, 2, 6, 1, 4);
        List<Integer> list2 = List.of(0, 1, 2, 0, 3, 2);
        List<Integer> tempList = new ArrayList<>();
        for (Integer i : list1) {
            tempList.add(list2.get(i - 1));
        }
        System.out.println(tempList);
    }
}

输出:

[3, 2, 1, 2, 0, 0]

[更新]

下面给出了一个更新的解决方案,以满足答案下方评论中提到的 OP 的新要求。

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main {

    public static void main(String[] args){
        List<Integer> list1 = List.of(15, 13, 12, 16, 11, 14);
        List<Integer> list2 = List.of(0, 1, 2, 0, 3, 2);
        List<Integer> tempList = new ArrayList<>();
        int max = Collections.max(list1);
        int offset = max - list2.size() + 1;
        for (Integer i : list1) {
            tempList.add(list2.get(i - offset));
        }
        System.out.println(tempList);
    }
}

输出:

[3, 2, 1, 2, 0, 0]

【讨论】:

  • 感谢您的回复,虽然我认为这看起来像是仅针对此问题的答案,但我想要一个适合各种测试用例的答案。列表 A 可以是:15、13、12、16、11、14;在这种情况下,我们不会得到这个答案。
  • @somuchsonal - 我已发布更新以满足此要求。如有任何问题/疑问,请随时发表评论。
  • @somuchsonal - 我希望该解决方案对您有用。不要忘记接受答案,以便将来的访问者也可以放心地使用该解决方案。检查meta.stackexchange.com/questions/5234/… 了解如何操作。如有任何疑问/问题,请随时发表评论。
猜你喜欢
  • 2020-12-04
  • 2012-08-11
  • 1970-01-01
  • 2018-02-09
  • 1970-01-01
  • 2015-04-17
  • 2020-09-08
  • 2020-07-03
  • 2013-10-22
相关资源
最近更新 更多