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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20126470/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 23:20:38  来源:igfitidea点击:

Java How To Keep Unique Values In A List of Objects

javalistmapunique

提问by Richard

I currently am retrieving a list of objects List<NprDto>(The NprDto class contains accountId, theDate1, and theDate2) from a query that returns results where the NprDto has duplicate accountIds. I need to have a List<NproDto>of only unique accountIds but keep the object. It only needs to add the first accountId it comes across and ignores the rest.

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

I'm currently trying this:

我目前正在尝试这个:

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;

}

But this doesn't seem to be working because when I iterate through the returned uniqueAccountsList later it only picks up the first object.

但这似乎不起作用,因为当我稍后遍历返回的 uniqueAccountsList 时,它只获取第一个对象。

Any help would be greatly appreciated.

任何帮助将不胜感激。

采纳答案by Masudul

I need to have a List of only unique accountIds but keep the object.

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

You should use Set<NprDto>. For that you need to override equalsand hasCodeat NproDtoclass.

你应该使用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();
 }
}


Change your getUniqueAccountListas follows:

更改您的getUniqueAccountList如下:

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

回答by noone

What you need to do is implement the equals, hashCodeand compareTomethods for NprDtoto match two objects as equal when their ID is the same. Then you can filter all duplicates as easy as this:

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

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

回答by Asif Bhutto

Actually you need to implements equals and hascode method, it will be good for you

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

Remove duplicates from a list

从列表中删除重复项

Java Set contains the Unique value but its unsorted collection. List is sorted collection but contains the duplicates objects.

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

回答by Adam Arold

What you need here is a LinkedHashSet. It removes duplicates and keeps insertion order. You do notneed TreeSethere because it sorts and changes the order of the original List.

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

If preserving insertion order is not important use a HashSet.

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