Tag Archives: remove duplicate values

Java : How to remove duplicate elements from List?


Here you will see way to remove duplicate from ArrayList. I am using HashSet because it keeps unique values only.

See Also : Java : How to remove duplicate objects from List

Example

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class RemoveDuplicateElements {
	public static void main(String[] args) {
		ListstrList=new ArrayList();
		strList.add("Facing");
		strList.add("Issues");
		strList.add("On");
		strList.add("IT");
		//duplicate
		strList.add("Facing");
		strList.add("IT");

		System.out.println("==========Before Duplicate Remove :"+strList.size());
		for(String str:strList)
		System.out.println(str);

		//Convert ArrayList to HashSet
		Set set=new HashSet(strList);
		//Convert HashSet to ArrayList
		strList=new ArrayList(set);

		System.out.println("==========After Duplicate Remove :"+strList.size());
		for(String str:strList)
		System.out.println(str);
	}
}

Output


==========Before Duplicate Remove :6
Facing
Issues
On
IT
Facing
IT
==========After Duplicate Remove :4
Facing
Issues
IT
On