我有值的mList2。有具有相同ID的值。我如何获得一个将具有相同ID的对象分组的List或ArrayList并将其添加到ArrayList>?
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).getIds_post().equals(mList2.get(j).getIds_post())) {
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);
Toast.makeText(context, group.toString(),Toast.LENGTH_SHORT ).show();
}
数据发布
data class DataPost(var text:String? = null, var photo:String? = null,
var type:String = "",
var ids_post:String = "", var position:String? = null)
最佳答案
使您的ProfileActivity.DataPost
类implements Comparable<ProfileActivity.DataPost>
接口,实现compareTo(ProfileActivity.DataPost o)
方法
@Override
public void compareTo(ProfileActivity.DataPost o){
return getIds_post().compareTo(o.getIds_post());
}
然后只需调用
Collections.sort(list)