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

标签 java list map unique

我目前正在检索对象列表 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> .为此,您需要覆盖 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;
}

关于Java 如何在对象列表中保持唯一值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20126470/

相关文章:

java - 如何对 Reactor Flux 流中的值求和?

java - 在java中使用字符串数组时,将其转换为小写

java - 当用户尝试通过 HTTP 连接时发回 HTTP 响应而不是堆栈跟踪

Haskell 中的函数列表

python - 从具有相同键的多个字典中获取值

java - Java 中数组中 String 的类型转换抛出 "Unknown Source Error"

plsql - 在pl/sql中映射数据结构以存储键值对?

c++ - 将文件流插入到 std::map

map - Dart ,一种更好的映射 map 的方式?

java - 没有定义 [javax.sql.DataSource] 类型的合格 bean