【问题标题】:arraylist rearrange with another arraylist [duplicate]arraylist 与另一个 arraylist 重新排列 [重复]
【发布时间】:2021-04-11 02:13:16
【问题描述】:

我想问一下arraylist重新排列

如果我有 2 个这样的数组列表

ArrayList<A> listA;
ArrayList<B> listB;

如果我像这样重新排列 listA

private static class Descending implements Comparator<A> {
    @Override
    public int compare(A arrayListA, A t1) {
        return t1.getLasttime().compareTo(arrayListA.getLasttime());
    }
}

private void setListTimeSort(ArrayList<A> arrayListA) {
    Descending descending = new Descending();
    Collections.sort(arrayListA, descending);
}

我想一起换位置listB。

简单示例:

listA before = 1, 2, 3, 4
listB before = a, b, c, d

如果 listA 改变 = 2, 1, 4, 3,我想 listB 改变相同位置 item = b, a, d, c.

我改变了listA,但我不知道如何改变listB(像listA一样改变位置)。

【问题讨论】:

  • 并行列表有点反模式,建议您改为使用类(或记录)来保存 A 和 B 值,并使用该类的实例填充单个列表。在这个解决方案中,只有一个列表可以排序,A 和 B 可以一起使用。

标签: java android arraylist position


【解决方案1】:

这显然假设两个列表的大小相同。

我将创建一个新的List&lt;Pair&lt;A,B&gt;&gt;,然后您可以迭代列表,从 ListA 和 ListB 中的相同位置的项目创建一个 Pair 对象。

然后使用比较器对配对的getKey() 部分进行比较,对配对列表(List&lt;Pair&lt;A,B&gt;&gt;)进行排序。

然后迭代排序后的列表,创建该对的getValue() 部分的列表。

(我可能会使用流,但这是基本思想)

【讨论】:

  • 也许你的解决方案对我有用.. 但是,你能给我举个简单的例子吗..?我搜索了“对”。但我无法理解.. :(
  • 我找到了解决方案。但我不知道在哪里可以分享
猜你喜欢
  • 1970-01-01
  • 2018-08-19
  • 1970-01-01
  • 2019-06-24
  • 2014-10-18
  • 2014-06-15
  • 1970-01-01
  • 1970-01-01
  • 2018-02-23
相关资源
最近更新 更多