我有一个bean列表,如何根据bean中的id删除重复项 告诉我如何以代码方式删除它?
List<Tasks>task =
[
{
"title": "Title1",
"description": "Description1",
"id": "123456"
},
{
"title": "Title2",
"description": "Description2",
"id": "123456"
},
{
"title": "Title3",
"description": "Description3",
"id": "123456"
},
{
"title": "Title4",
"description": "Description4",
"id": "654321"
}
]
我的预期输出是id = 123456和654321
列表中的任何一个[
{
"title": "Title2",
"description": "Description2",
"id": "123456"
},
{
"title": "Title4",
"description": "Description4",
"id": "654321"
}
]
答案 0 :(得分:1)
Map<String, Task> map = new HashMap<>():
tasks.forEach(t -> map.put(t.getId(), t);
Collection<Task> withoutDuplicates = map.values();
答案 1 :(得分:-2)
您可以在bean类中添加equals方法。
@Override
public boolean equals(Object obj) {
if(id.equals((YourBeanClass)obj).id)
return true;
return false;
}
其中id是Bean对象Id。
并且用于存储ArrayList
数据使用LinkedHashSet
这将避免重复。或者如果您使用ArrayList
,您可以使用contains方法在添加之前检查Bean对象是否已存在。