Home Tutorial Java Core Remove duplicates from ArrayList

 
 

Share on Google+Share on Google+
Remove duplicates from ArrayList
Posted on: May 22, 2010 at 12:00 AM
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
Advertisement

Related Tags for Remove duplicates from ArrayList:


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.

Posted on: May 22, 2010

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com