Java如何在对象列表中保留唯一值

Ric*_*ard 3 java list unique map

我目前正在从查询中检索对象列表List<NprDto>(NprDto类包含accountId,theDate1和theDate2),该查询返回NprDto具有重复accountIds的结果.我需要一个List<NproDto>唯一的唯一accountIds但保留对象.它只需要添加它遇到的第一个accountId并忽略其余的.

我正在尝试这个:

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;

}
Run Code Online (Sandbox Code Playgroud)

但这似乎没有用,因为当我迭代返回的uniqueAccountsList后,它只会拾取第一个对象.

任何帮助将不胜感激.

Mas*_*dul 10

我需要一个只有唯一的accountIds列表,但保留对象.

你应该用Set<NprDto>.对于您需要重写equals,并hasCodeNproDto类.

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();
 }
}
Run Code Online (Sandbox Code Playgroud)

改变你的getUniqueAccountList如下:

private Set<NprDto> getUniqueAccountSet(){    
  Map<Long,NprDto> uniqueAccountsMapList = new HashMap<Long,NprDto>();
  Set<NprDto> uniqueAccs = new HashSet<NprDto>(uniqueAccountsMapList.values());    
  return uniqueAccs;
}
Run Code Online (Sandbox Code Playgroud)


Ada*_*old 7

你需要的是一个LinkedHashSet.它删除重复项并保持插入顺序.你并不需要TreeSet,因为它排序,并改变原来的顺序位置List.

如果保留插入顺序不重要,请使用a HashSet.