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:
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 employeeNameList = new ArrayList();
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 uniqueElements = new ArrayList();
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(new HashSet(
employeeNameList));
for (String uniqElem : uniqueElements) {
System.out.println(uniqElem);
}
System.out.println("*******************************");
System.out.println("Using LinkedHashSet :");
// using LinkedHashSet maintaining order
uniqueElements = new ArrayList(new LinkedHashSet(
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.