2017-04-04 90 views
0

我有一個類型的集合的集合Person去除重複基於條件

class Person { 
    String firstName; 
    String lastName; 
} 

我想從這個名單中刪除重複的基礎上,條件 - 如果有列表中的兩個元素具有 相同的名字, 和姓氏在一個名字中,另一個名字爲空, 然後具有姓氏的名字只保留在列表中。

對於例如: 如果有2種元素在列表中,像

  1. 的firstName = 「約翰」,姓氏= 「Doe的」
  2. 的firstName = 「約翰」,姓氏= NULL

只有John Doe應保留在列表中。 在lastName可能爲null的情況下,只要它不與列表中的另一個元素共享firstName

另外,我有一個爲每個處理這些信息,

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

我怎樣才能以最優化的方式實現這一目標。任何幫助不勝感激。

+0

那你至今呢? – IQV

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

謝謝!這對我有效 – Raskill