我目前正在检索对象列表 List<NprDto>
(NprDto 类包含 accountId、theDate1 和 theDate2)来自返回结果的查询,其中 NprDto 具有重复的 accountId。我需要一个 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;
}
但这似乎不起作用,因为当我稍后遍历返回的 uniqueAccountsList 时,它只拾取第一个对象。
如有任何帮助,我们将不胜感激。
最佳答案
I need to have a List of only unique accountIds but keep the object.
你应该使用 Set<NprDto>
.为此,您需要覆盖 equals
和 hasCode
在NproDto
类。
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;
}
关于Java 如何在对象列表中保持唯一值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20126470/