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
Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s