【问题标题】:Java How To Keep Unique Values In A List of ObjectsJava如何在对象列表中保持唯一值
【发布时间】:2013-12-06 05:56:45
【问题描述】:

我目前正在从返回 NprDto 具有重复 accountId 的结果的查询中检索对象列表 List<NprDto>(NprDto 类包含 accountId、theDate1 和 theDate2)。我需要一个只有唯一帐户 ID 的 List<NproDto>,但要保留该对象。它只需要添加它遇到的第一个 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 时,它只会拾取第一个对象。

任何帮助将不胜感激。

【问题讨论】:

  • 您确定您有唯一的帐号吗?我认为您的设计很好(节省了您做 Set 所需的大量工作),而且您的代码看起来也不错。我打赌你的问题出在其他地方。
  • 我的输出语句位置错误。一切正常。谢谢!

标签: java list map unique


【解决方案1】:

我需要一个仅包含唯一帐户 ID 的列表,但要保留 对象。

您应该使用Set&lt;NprDto&gt;。为此,您需要在 NproDto 类中覆盖 equalshasCode

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;
}

【讨论】:

    【解决方案2】:

    您需要的是LinkedHashSet。它删除重复项并保持插入顺序。 您不需要在这里需要TreeSet,因为它会排序并更改原始List 的顺序。

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

    【讨论】:

      【解决方案3】:

      其实你需要实现equals和hascode方法,对你有好处

      Remove duplicates from a list

      Java Set 包含唯一值但它的未排序集合。 List 是排序的集合,但包含重复的对象。

      【讨论】:

        【解决方案4】:

        您需要做的是为NprDto 实现equalshashCodecompareTo 方法,以在两个对象的ID 相同时将其匹配为相等。然后您可以像这样简单地过滤所有重复项:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2022-06-22
          • 2019-07-13
          • 2014-11-20
          • 1970-01-01
          • 2021-03-12
          • 2016-08-07
          • 1970-01-01
          相关资源
          最近更新 更多