Richard
Richard

Reputation: 826

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.

Upvotes: 3

Views: 21142

Answers (4)

Masudul
Masudul

Reputation: 21961

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

Upvotes: 10

Adam Arold
Adam Arold

Reputation: 30528

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.

Upvotes: 6

Asif Bhutto
Asif Bhutto

Reputation: 3994

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.

Upvotes: 0

noone
noone

Reputation: 19776

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

Upvotes: -1

Related Questions