Tutorials Java How to Remove Duplicate Values From Java ArrayList

How to Remove Duplicate Values From Java ArrayList

This example shows how to remove duplicate from ArrayList. The easiest way to remove duplicate is by passing the List to an Set. As set doesn’t support duplicates it will omit the duplicate values. Once you have the Set you can again pass it back to ArrayList.

Duplicate Values From Java ArrayList using HashSet

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

public class RemoveDuplicate {
	public static void main(String[] args) {
		List sourceList = new ArrayList();

		sourceList.add("object1");
		sourceList.add("object2");
		sourceList.add("object2");
		sourceList.add("object3");
		sourceList.add("object4");
		sourceList.add("object2");

		List newList = new ArrayList(new HashSet(
				sourceList));
		Iterator it = newList.iterator();
		while (it.hasNext()) {
			System.out.println(it.next());
		}

	}
}

Output

object3
object4
object1
object2

In this above example we have removed duplicates from the ArrayList but we will loose the sequencing index. If you want to preserve the order of data use LinkedHashSet rather HashSet. Find an example below

Duplicate Values From Java ArrayList using LinkedHashSet

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;

public class RemoveDuplicate {
	public static void main(String[] args) {
		List sourceList = new ArrayList();

		sourceList.add("object1");
		sourceList.add("object2");
		sourceList.add("object2");
		sourceList.add("object3");
		sourceList.add("object4");
		sourceList.add("object2");

		List newList = new ArrayList(new LinkedHashSet(
				sourceList));
		Iterator it = newList.iterator();
		while (it.hasNext()) {
			System.out.println(it.next());
		}

	}
}

Output

object1
object2
object3
object4
Total
0
Shares
guest
0 Comments
Inline Feedbacks
View all comments
Previous Post
Eclipse Tutorials and Plugins

How to Instal SVN Subversive Plug-In in eclipse

Next Post
Java Tutorials

Introduction to Java, JVM and Writing Your Fist Java Program

Related Posts
By clicking “Allow All”, you agree to the storing of cookies on your device to enhance site navigation, analyze site usage, and assist in our marketing efforts. Cookie Notice
Allow All
0
Would love your thoughts, please comment.x
()
x