简体   繁体   中英

Java How To Keep Unique Values In A List of Objects

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.

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.

Any help would be greatly appreciated.

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

You should use Set<NprDto> . For that you need to override equals and hasCode at NproDto class.

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 getUniqueAccountList as follows:

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

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

If preserving insertion order is not important use a HashSet .

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

Remove duplicates from a list

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

What you need to do is implement the equals , hashCode and compareTo methods for NprDto to match two objects as equal when their ID is the same. Then you can filter all duplicates as easy as this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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