gpt4 book ai didi

java - 如何按 id 对 ArrayList 进行排序并添加到 ArrayList>

转载 作者:行者123 更新时间:2023-12-02 09:25:30 24 4
gpt4 key购买 nike

我有带有值的 mList2。存在具有相同 id 的值。如何获取具有相同 id 的对象分组的 List 或 ArrayList 并将其添加到 ArrayList 的 ArrayList

应该是这样:

ArrayList<ArrayList<DataPost>> = [DataPost(with id1), DataPost(with id1), DataPost(with id1)],
[DataPost(with id2), DataPost(with id2)],
[DataPost(with id3), DataPost(with id3)],
[DataPost(with id4)],
[DataPost(with id5)].

此代码适用于 List,但不适用于 PostData

public static List<List<ProfileActivity.DataPost>> SortMyList(ArrayList<ProfileActivity.DataPost> list, Context context) {
List<ProfileActivity.DataPost> mList2 = list;
List<List<ProfileActivity.DataPost>> output = new ArrayList<List<ProfileActivity.DataPost>>();
List<ProfileActivity.DataPost> itemsAlreadyGrouped = new ArrayList<ProfileActivity.DataPost>();
for (int i = 0; i < mList2.size(); i++) {
List<ProfileActivity.DataPost> groupList = new ArrayList<ProfileActivity.DataPost>();
boolean groupCandidateFound = false;
if (!itemsAlreadyGrouped.contains(mList2.get(i))) {
for (int j = 0; j < mList2.size(); j++) {
if (mList2.get(i).component4().equals(mList2.get(j).component4())) {
groupList.add(mList2.get(i));
groupCandidateFound = true;
}
}
if (groupCandidateFound) {
itemsAlreadyGrouped.add(mList2.get(i));
}
}
if (groupList.size() > 0) {
output.add(groupList);
}
}

//Let's test the logic
for (List<ProfileActivity.DataPost> group : output) {
System.out.println(group);
}
return output;
}

DataPost

data class DataPost(var text:String? = null, var type:String = "", var photo:String? =null, var  ids_post:String = "", var position: String? = null)

最佳答案

执行此类分组的最简单方法是使用 map 。在 Kotlin 中这非常简单,因为它已经有一个函数可以做到这一点。

fun groupAndSort(posts: Collection<DataPost>): List<List<DataPost>> {
val map = TreeMap<String, MutableList<DataPost>>()
posts.groupByTo(map) { it.ids_post }
return map.values.toList()
}

如果您需要 Java 解决方案,那么实现起来相当容易。

public List<List<DataPost>> sortAndGroup(Collection<DataPost> posts) {
Map<String, List<DataPost>> groups = new TreeMap<>();
for (DataPost post : posts) {
String id = post.getIds_post();
List<DataPost> list = groups.get(id);
if (list == null) {
list = new ArrayList<>();
groups.put(id, list);
}
list.add(post);
}
return new ArrayList<>(groups.values());
}

关于java - 如何按 id 对 ArrayList 进行排序并添加到 ArrayList<ArrayList<DataPost>>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58366886/

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