Java – Conversion of ArrayList into HashSet to remove duplicate elements

In this article, we will discuss how to remove duplicate elements from ArrayList

Q) How to convert ArrayList to HashSet ?

  • use inter-conversion collection constructor
  • Syntax :
Set<T> set = new HashSet<T>(alObj); 

To remove duplicate elements from ArrayList :

Steps:

  1. Iterate through ArrayList to check duplicate elements
  2. Create HashSet using inter-conversion collection constructors
  3. Add ArrayList object to constructor argument
  4. Again, iterate through HashSet which stores only unique elements
  5. If NULL is present; maximum of one NULL element is allowed

ConvertArrayListToHashSet.java

package in.bench.resources.java.collections;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;

public class ConvertArrayListToHashSet {

	public static void main(String[] args) {

		// creating ArrayList object of type String
		ArrayList<String> fruits = new ArrayList<String>();

		// adding elements to ArrayList object
		fruits.add("Apple");
		fruits.add("Greeplum");
		fruits.add("Blackberry");
		fruits.add("Apple"); // duplicate
		fruits.add("Mango");
		fruits.add("Orange");
		fruits.add("Greeplum"); // duplicate

		// Iterating using enhanced for-loop
		System.out.println("ArrayList as per Insertion Order:\n");
		for(String fruit : fruits) {
			System.out.println(fruit);
		}

		// remove duplicates by converting to HashSet
		// convert to HashSet
		Collection<String> hsetFruits = new HashSet<String>(fruits);

		// Iterating using enhanced for-loop
		System.out.println("\n\nUnique Fruit of AL\n");
		for(String name : hsetFruits) {
			System.out.println(name);
		}
	}
}

Output:

ArrayList as per Insertion Order:

Apple
Greeplum
Blackberry
Apple
Mango
Orange
Greeplum

Unique Fruit of AL

Blackberry
Greeplum
Orange
Apple
Mango

From above example, ArrayList

  • allows duplicate elements
  • null object is allowed
  • while iterating insertion-order is maintained

From above example, HashSet

  • doesn’t allow duplicate elements
  • maximum of one null object is allowed
  • while iterating, retrieve elements in random-order

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java - How to convert LinkedList to contain unique elements in Ascending-order ?
Java - Iterate through Vector in 5 ways