根据条件删除集合中的重复项

时间:2017-04-04 09:20:55

标签: java list collections foreach

我有一个Person

类型的集合
class Person {
    String firstName;
    String lastName;
}

我想根据条件删除此列表中的重复项 - 如果列表中有两个元素具有相同的名字, 名字在一个中的姓氏和另一个名称为null, 那么姓氏的名字只保留在名单中。

对于Eg: 如果列表中有2个元素,比如

  1. firstName =" John",lastName =" Doe"
  2. firstName =" John",lastName = null
  3. 只有 John Doe 应保留在列表中。 可能存在这样的情况:lastName可以为空,前提是它不与列表中的另一个元素共享相同的firstName

    另外,我每个处理此信息都有一个,

    for(Person person : Persons) {
    //I would like the duplication removal happening here
    /*process(person)*/
    }
    

    如何以最佳方式实现这一目标。非常感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

    List<Person> persons = Arrays.asList(
    new Person("Tom","White"),
    new Person("Mark",null  ),
    new Person("Tom","Brown"),
    new Person("John","Doe" ),
    new Person("Tom","Black"),
    new Person("John",null  ),
    new Person("Tom",null));

    Map<String,Person> pmap = new TreeMap<String,Person>();

    for (Person p : persons) {
        Person other = pmap.get(p.firstName);
        if(other==null || other.lastName==null){
            pmap.put(p.firstName, p);
        }
    }
    System.out.println(pmap.values());

输出

Person [firstName=John, lastName=Doe], Person [firstName=Mark, lastName=null], Person [firstName=Tom, lastName=White]]