The Artima Developer Community
Sponsored Link

Java Buzz Forum
How to Remove Duplicates from ArrayList in Java

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Javin Paul

Posts: 1090
Nickname: javinpaul
Registered: Jan, 2012

Javin Paul is Java Programmer working on Finance domain.
How to Remove Duplicates from ArrayList in Java Posted: Mar 24, 2015 8:17 AM
Reply to this message Reply

This post originated from an RSS feed registered with Java Buzz by Javin Paul.
Original Post: How to Remove Duplicates from ArrayList in Java
Feed Title: Java67
Feed URL: http://www.java67.com/feeds/posts/default?alt=rss
Feed Description: Java and technology tutorials, tips, questions for all programmers.
Latest Java Buzz Posts
Latest Java Buzz Posts by Javin Paul
Latest Posts From Java67

Advertisement
ArrayList is the most popular implementation of List interface from Java's Collection framework, but it allow duplicates. Though there is another collection called Set which is primarily designed to store unique elements, there are situations when you receive a List e.g. ArrayList in your code and you need to ensure that it doesn't contain any duplicate before processing. Since with ArrayList you cannot guarantee uniqueness, there is no other choice but to remove repeated elements from ArrayList. There are multiple ways to do this, you can follow the approach we used for removing duplicates from array in Java, where we loop through array and inserting each element in a Set, which ensures that we discard duplicate because Set doesn't allow them to insert, or you can also use remove method of ArrayList to get rid of them, once you found that those are duplicates, but the simplest approach to remove repeated objects from ArrayList is to copy them to a Set e.g. HashSet and then copy it back to ArrayList. This will remove all duplicates without writing any more code. One thing to noted is that, if original order of elements in ArrayList is important for you, as List maintains insertion order, you should use LinkedHashSet because HashSet doesn't provide any ordering guarantee. BTW, if you are using deleting duplicates while iterating, make sure you use Iterator's remove() method and not the ArrayList one to avoid ConcurrentModificationException.  In this tutorial we will see this approach to remove duplicates.
Read more »

Read: How to Remove Duplicates from ArrayList in Java

Topic: Jdbc Connction Steps with Examples Previous Topic   Next Topic Topic: Java : Collection Framework : ArrayList Vs. HashSet

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use