How to remove duplicates from ArrayList in java

In this post, we will see how to remove duplicate elements from ArrayList in java.
There are many ways to do it. Some of them are:
  • Using iterative approach
  • Using HashSet (but does not maintain insertion order)
  • Using LinkedHashMap

Program:

package org.arpit.java2blog.algo;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.*;

public class RemoveDuplicatesArrayListMain {
 /*
  * @author : Arpit Mandliya
  */
 public static void main(String[] args) {
  ArrayList<String> employeeNameList = new ArrayList<String>();
  employeeNameList.add("John");
  employeeNameList.add("Ankit");
  employeeNameList.add("Rohan");
  employeeNameList.add("John");
  employeeNameList.add("Amit");
  employeeNameList.add("Ankit");

  System.out.println("Removing duplicates from list:");
  // Using iterative approach
  ArrayList<String> uniqueElements = new ArrayList<String>();
  for (String empName : employeeNameList) {

   if (!uniqueElements.contains(empName)) {
    uniqueElements.add(empName);
   }
  }
  
  System.out.println("Using iterative approach:");
  for (String uniqElem : uniqueElements) {
   System.out.println(uniqElem);
  }
  System.out.println("*******************************");
  System.out.println("Using HashSet :");
  // using HashSet but does not maintain order
  uniqueElements = new ArrayList<String>(new HashSet<String>(
    employeeNameList));
  for (String uniqElem : uniqueElements) {
   System.out.println(uniqElem);
  }
  System.out.println("*******************************");
  System.out.println("Using LinkedHashSet :");
  // using LinkedHashSet maintaining order
  uniqueElements = new ArrayList<String>(new LinkedHashSet<String>(
    employeeNameList));
  for (String uniqElem : uniqueElements) {
   System.out.println(uniqElem);
  }

 }
}
When you run above program, you will get following output:
Removing duplicates from list:
Using iterative approach:
John
Ankit
Rohan
Amit
*******************************
Using HashSet :
Rohan
Ankit
Amit
John
*******************************
Using LinkedHashSet :
John
Ankit
Rohan
Amit

Please go through java interview programs for more such programs.

Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus

 

Java tutorial for beginners Copyright © 2012