如何按ID对ArrayList排序并添加到ArrayList <ArrayList <DataPost >>

时间:2019-10-13 19:05:57

标签: java android list kotlin arraylist

我有带有值的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)].

此代码适用于列表,但不适用于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;
}

数据发布

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

1 个答案:

答案 0 :(得分:1)

执行此类分组的最简单方法是使用地图。在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());
}