如何使用java从bean中删除基于id的重复项?

时间:2016-11-26 10:22:43

标签: java

我有一个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"

    }
]

2 个答案:

答案 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对象是否已存在。