gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 02:55:10 24 4
gpt4 key购买 nike

我有一个 Person 类型的集合

class Person {
String firstName;
String lastName;
}

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

例如:如果列表中有 2 个元素,例如

  1. 名字 =“约翰”,姓氏 =“Doe”
  2. 名字 =“约翰”,姓氏 = null

只有John Doe应该保留在列表中。在某些情况下,如果 lastName 不与列表中的另一个元素共享相同的 firstName,则它可能为 null。

另外,我有一个 for every 处理此信息,

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

我怎样才能以最优化的方式实现这一目标。非常感谢任何帮助。

最佳答案

    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]]

关于java - 根据条件删除集合中的重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43203081/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com