title: Java How To Keep Unique Values In A List of Objects
body: <p>I currently am retrieving a list of objects <code>List&lt;NprDto&gt;</code> (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 <code>List&lt;NproDto&gt;</code> of only unique accountIds but keep the object. It only needs to add the first accountId it comes across and ignores the rest. </p>
  
  <p>I'm currently trying this:</p>
  
  <pre><code>private List&lt;NprDto&gt; getUniqueAccountList(List&lt;NprDto&gt; nonUniqueAccountList) throws Exception {
  
      Map&lt;Long,NprDto&gt; uniqueAccountsMapList = new HashMap&lt;Long,NprDto&gt;();
      List&lt;NprDto&gt; uniqueAccountsList = null;
  
      if(nonUniqueAccountList != null &amp;&amp; !nonUniqueAccountList.isEmpty()) {
          for(NprDto nprDto : nonUniqueAccountList) {
              uniqueAccountsMapList.put(Long.valueOf(nprDto.getAccountId()), nprDto);
          }
      }
  
      uniqueAccountsList = new ArrayList&lt;NprDto&gt;(uniqueAccountsMapList.values());
  
      return uniqueAccountsList;
  
  }
  </code></pre>
  
  <p>But this doesn't seem to be  working because when I iterate through the returned uniqueAccountsList later it only picks up the first object.</p>
  
  <p>Any help would be greatly appreciated.</p>