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:
When you run above program, you will get following output:
Please go through java interview programs for more such programs.
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
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); } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
Removing duplicates from list: Using iterative approach: John Ankit Rohan Amit ******************************* Using HashSet : Rohan Ankit Amit John ******************************* Using LinkedHashSet : John Ankit Rohan Amit |
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.