2013-11-21 73 views
3

我目前正在從查詢中檢索對象列表List<NprDto>(NprDto類包含accountId,theDate1和theDate2),該查詢返回NprDto具有重複accountIds的結果。我需要有一個唯一的accountId List<NproDto>但保留該對象。它只需要添加遇到的第一個accountId並忽略其餘部分。Java如何在對象列表中保留唯一值

目前,我正在嘗試此:

private List<NprDto> getUniqueAccountList(List<NprDto> nonUniqueAccountList) throws Exception { 

    Map<Long,NprDto> uniqueAccountsMapList = new HashMap<Long,NprDto>(); 
    List<NprDto> uniqueAccountsList = null; 

    if(nonUniqueAccountList != null && !nonUniqueAccountList.isEmpty()) { 
     for(NprDto nprDto : nonUniqueAccountList) { 
      uniqueAccountsMapList.put(Long.valueOf(nprDto.getAccountId()), nprDto); 
     } 
    } 

    uniqueAccountsList = new ArrayList<NprDto>(uniqueAccountsMapList.values()); 

    return uniqueAccountsList; 

} 

但這似乎並不奏效,因爲當我通過返回uniqueAccountsList迭代後,它只能拿起第一個對象。

任何幫助將不勝感激。

+0

你確定你有唯一的帳號嗎?我認爲你的設計很好(節省了你做Set所需的大量工作),而且你的代碼看起來也不錯。我敢打賭你的問題在別的地方。 – RalphChapin

+0

我有一個輸出語句在錯誤的位置。一切工作正常。謝謝! – Richard

回答

10

我需要一個唯一的accountIds列表,但保留 對象。

您應該使用Set<NprDto>。爲此,您需要覆蓋equalshasCodeNproDto類。

class NprDto{ 
    Long accountId; 
    ....... 

@Override 
public boolean equals(Object obj) { 
    NproDto other=(NproDto) obj; 
    return this.accountId==other.accountId; 
} 

@Override 
public int hashCode() { 
    return accountId.hashCode(); 
} 
} 

更改getUniqueAccountList如下:

private Set<NprDto> getUniqueAccountSet(){  
    Map<Long,NprDto> uniqueAccountsMapList = new HashMap<Long,NprDto>(); 
    Set<NprDto> uniqueAccs = new HashSet<NprDto>(uniqueAccountsMapList.values());  
    return uniqueAccs; 
} 
-1

你需要做的是落實equalshashCodecompareTo方法NprDto匹配兩個對象是相等的,當他們的ID是相同。然後你就可以過濾所有重複的那麼容易,因爲這樣的:

private List<NprDto> getUniqueAccountList(List<NprDto> nonUniqueAccountList) { 
    return new ArrayList<NprDto>(new LinkedHashSet<NprDto>(nonUniqueAccountList)); 
} 
0

其實你需要實現equals和hascode方法,這將是對你有好處

Remove duplicates from a list

的Java套件包括獨特的價值,但其未分類收集。列表是排序的集合,但包含重複的對象。

5

您需要的是LinkedHashSet。它刪除重複並保持廣告訂單。 您不需要需要TreeSet這裏因爲它排序和更改原始List的順序。

如果保留插入順序不重要,請使用HashSet

相關問題