gpt4 book ai didi

java - 如何根据两个数组列表的大小将其排序到一个新的数组列表中

转载 作者:行者123 更新时间:2023-12-01 16:11:38 26 4
gpt4 key购买 nike

我有两个对象,每个对象都有一个 id 和一个列表。我希望有第三个 arraylist 根据列表大小对该对象进行排序。并且仍然具有相应的 id 和列表

最佳答案

方法如下:

  1. 创建 Comparator它可以比较两个“id/列表对”——在本例中,我们比较列表组件的列表大小。

  2. 创建 ArrayList这些“id/列表对”。

  3. 使用Collections.sort方法根据 Comparator 对 ArrayList 进行排序。

如果我理解正确的话,有一个 id/list 对。这是我制作的:

class IdListPair {
int id;
List<?> list;

IdListPair(int id, List<?> list) {
this.id = id;
this.list = list;
}

public String toString() {
return "id: " + id + "; list: " + list;
}
}

IdListPair 提供了一个构造函数来创建 id/list 对,以及一个 toString 方法,稍后将使用该方法来显示排序结果。

然后,我们将有一个部分创建一个 ArrayList,并使用 Comparator 对列表进行排序:

List<IdListPair> pairList = new ArrayList<IdListPair>();
pairList.add(new IdListPair(0, Arrays.asList(1, 2, 3)));
pairList.add(new IdListPair(1, Arrays.asList(1)));
pairList.add(new IdListPair(2, Arrays.asList(1, 2)));

System.out.println("Before: " + pairList);

Collections.sort(pairList, new Comparator<IdListPair>() {
public int compare(IdListPair o1, IdListPair o2) {
return o1.list.size() - o2.list.size();
}

public boolean equals(Object o) {
return false;
}
});

System.out.println("After: " + pairList);

首先,使用 IdListPair 创建一个 ArrayList,其中包含不同长度的列表。

然后,Collections.sort方法根据 Comparator 提供的规则执行排序。实现Comparator的类需要提供compareequals方法。

这里创建了一个Comparator,因此它将比较 size compare 中每个 IdListPair 对象包含的 list方法。 equals 方法是一个虚拟方法,因为此处未使用它。

大部分工作将用于编写正确的 compare 方法,以便 Collections.sort 的排序器可以正确地对列表进行排序。

结果如下:

Before: [id: 0; list: [1, 2, 3], id: 1; list: [1], id: 2; list: [1, 2]]
After: [id: 1; list: [1], id: 2; list: [1, 2], id: 0; list: [1, 2, 3]]

关于java - 如何根据两个数组列表的大小将其排序到一个新的数组列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1011410/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com