StackTips

How to Remove Duplicate Values From Java ArrayList

stacktips avtar

Written by

Editorial,  3 min read,  2.71K views, updated on Sept. 17, 2023

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

Beginner's Guide to Java Collections

This course covers the fundamentals of java collections framework covering different data structures in Java to store, group, and retrieve objects.

>> CHECK OUT THE COURSE
stacktips avtar

Editorial

StackTips provides programming tutorials, how-to guides and code snippets on different programming languages.

Related posts

Let’s be friends!

🙌 Stay connected with us on social media for the latest updates, exclusive content, and more. Follow us now and be part of the conversation!