繁体   English   中英

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

[英]Java How To Keep Unique Values In A List of Objects

我目前正在从查询中检索对象List<NprDto> (NprDto类包含accountId,theDate1和theDate2),该查询返回NprDto具有重复accountIds的结果。 我需要一个只有唯一accountIds的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后,它只会拾取第一个对象。

任何帮助将不胜感激。

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

您应该使用Set<NprDto> 为此,您需要在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;
}

你需要的是LinkedHashSet 它删除重复项并保持插入顺序。 不需要 TreeSet这里,因为它排序,并改变原来的顺序List

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

实际上你需要实现equals和hascode方法,这对你有好处

从列表中删除重复项

Java Set包含Unique值但其未排序的集合。 列表是已排序的集合,但包含重复项对象。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM