Remove duplicates from ArrayList


 

Remove duplicates from ArrayList

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

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

Ads