Share on Google+Share on Google+

Remove duplicates from ArrayList

Advertisement
In this section, you will learn how to remove duplicate values from ArrayList.

Remove duplicates from ArrayList

Sometimes we added large amount of data to ArrayList  where some values will get added twice or thrice which may conflict. So It is better to remove them. The easiest way to remove repeated elements is to add the contents to a Set (which will not allow duplicates) and then add the Set back to the ArrayList.

Here is the code:

import java.util.*;

public class RemoveDuplicate {
	public static void removeDuplicates(ArrayList list) {
		HashSet set = new HashSet(list);
		list.clear();
		list.addAll(set);
	}

	public static void main(String args[]) {
		ArrayList list = new ArrayList();
		list.add("a");
		list.add("b");
		list.add("a");
		list.add("c");
		list.add("b");
		removeDuplicates(list);
		System.out.println("ArrayList : ");
		for (Object data : list) {
			System.out.println(data);
		}
	}
}

Output:

ArrayList:
b
c
a

Advertisements

Advertisement

Posted on: May 22, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.