简体   繁体   English

收集实用程序删除重复对象

[英]Collection Utils removing duplicates object

I have an Object Person(id, name). 我有一个对象Person(id,name)。

public class Person {


/** Personid. **/
private Long personId;

/** Person Adresse. **/
private String adresse

// Getters, Setters

How can i remove duplicate person (who have same id) using CollectionUtils ? 如何使用CollectionUtils删除重复的人(具有相同的ID)? For example Person1(10, aaaa), Person2(10, bbbb), Person3(20, cccc) Result => Person1(10, aaaa), Person3(30, cccc) 例如Person1(10,aaaa),Person2(10,bbbb),Person3(20,cccc)结果=> Person1(10,aaaa),Person3(30,cccc)

EDIT : 编辑:

This Solution work using Set and overrinding equals and hashcode: 此解决方案使用Set并覆盖等于和哈希码进行工作:

List<Person> oldPerson = new ArrayList<>();
//oldPerson.add ...

Set<Person> newPerson = new HashSet<>(oldPerson);

List<Person> theRightPerson = new ArrayList<>(newPerson);

The solution that im looking for is something like : 我正在寻找的解决方案是这样的:

 List<Person> theRightPerson = (List<Person>) CollectionUtils.collect(oldPerson, new Transformer() {

        @Override
        public Object transform(Object input) {
            // TODO Auto-generated method stub
            return null;
        }
    })

Overriding equals and hashcode methods and using HashSet would be easier to do. 覆盖equals和hashcode方法以及使用HashSet会更容易实现。 If you can't edit the source of the class, then you need to iterate over the list and compare each item based on criteria. 如果您无法编辑类的源代码,则需要遍历列表并根据条件比较每个项目。

How to remove duplicate objects in a List<MyObject> without equals/hashcode? 如何在没有equals / hashcode的List <MyObject>中删除重复的对象?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM