首页 > 解决方案 > Java ArrayList 按相同顺序对两个列表进行排序

问题描述

我在 Java 中有两个 ArrayList。两个列表都未排序。

    ArrayList<Integer> listOne = new ArrayList<>();
    listOne.add(2);
    listOne.add(1);
    listOne.add(4);
    listOne.add(8);
    listOne.add(6);

    ArrayList<String> listTwo = new ArrayList<>();
    listTwo.add("ant");
    listTwo.add("bear");
    listTwo.add("cat");
    listTwo.add("dog");
    listTwo.add("zebra");

我想按自然顺序对 listOne 进行排序,并且 listTwo 的每个项目都应根据 listOne 中的位置进行排序:

到目前为止,我所拥有的是:

  Collections.sort(listOne);

  for (int i = 0; i < listOne.size(); i++) {

        int intTest = listOne.get(i);
        String stringTest = listTwo.get(i);

        System.out.println(intTest);
        System.out.println(stringTest);

    }

这打印:

  1 ant, 2 bear, 4 cat , 6 dog , 8 zebra

我预期的打印输出是:

  1 bear, 2 ant, 4 cat, 6 zebra, 8 dog

因此,当 listOne 的项目“1”将位置从第 2 位更改为第 1 位时,listTwo 中位于第 2 位的项目“bear”也应该打印在第 1 位。

最简单有效的方法是什么?

标签: javasortingarraylist

解决方案


创建一个有序的索引列表:

int n = listOne.size();
assert n == listTwo.size();

Integer[] indices = new Integer[n];
for (int i = 0; i < n; ++i) {
  indices[i] = i;
}

使用比较器对该列表进行排序,该比较器通过查看 listOne 中的相应元素来比较索引。

Arrays.sort(
    indices,
    new Comparator<Integer>() {
      public int compare(Integer a, Integer b) {
        return listOne.get(a).compareTo(listOne.get(b));
      }
    });

现在您可以使用索引对两个列表重新排序:

static <T> void reorder(Integer[] indices, List<T> mutatedInPlace) {
  List<T> tempSpace = new ArrayList<T>(indices.length);
  for (int index : indices) {
    tempSpace.add(mutatedInPlace.get(index);
  }
  mutatedInPlace.clear();
  mutatedInPlace.addAll(tempSpace);
}

reorder(indices, listOne);
reorder(indices, listTwo);

推荐阅读