How to remove duplicate elements from ArrayList maintaining insertion order

In this article, we will discuss how to remove duplicate elements from ArrayList maintaining its insertion-order

 

Solution:

  • simply, convert to LinkedHashSet

 

Remove duplicate elements from ArrayList :

Steps:

  1. Iterate through ArrayList to understand insertion-order
  2. Create LinkedHashSet using inter-conversion collection constructors
  3. Add ArrayList object to constructor argument
  4. Again, iterate through LinkedHashSet which maintains insertion-order removing duplicate elements from ArrayList

ArrayListPushToLinkedHashSet.java

package in.bench.resources.java.collections;

import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashSet;

public class ArrayListPushToLinkedHashSet {

	public static void main(String[] args) {

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

		// adding elements to ArrayList object
		techCompanies.add("Sun");
		techCompanies.add("Apple");  
		techCompanies.add("JBoss"); 
		techCompanies.add("Whatsup");
		techCompanies.add("Apple");
		techCompanies.add("BEA Weblogic");
		techCompanies.add("JBoss");

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

		// remove duplicates, maintaining insertion order

		// convert to LinkedHashSet
		Collection<String> lhs = new LinkedHashSet<String>(techCompanies);

		// Iterating using enhanced for-loop
		System.out.println("\n\nUnique elements and Insertion order\n");
		for(String techCompany : lhs) {
			System.out.println(techCompany);
		}
	}
}

Output:

ArrayList as per Insertion Order:

Sun
Apple
JBoss
Whatsup
Apple
BEA Weblogic
JBoss


Unique elements and Insertion order

Sun
Apple
JBoss
Whatsup
BEA Weblogic

Note :

 

References:

 

Happy Coding !!
Happy Learning !!

Conversion of LinkedList into Vector
Queue’s push and pop operations with LinkedList from Java 1.5 version