Learnitweb

How to remove duplicates from ArrayList?

The task is to remove duplicate elements from the ArrayList. For Example:

Input: [1, 2, 2, 5, 10, 21, 5, 3, 8, 9, 0, 3]
Output: [1, 2, 5, 10, 21, 3, 8, 9, 0]

Approach 1 – Using Iterator

  • Get first ArrayList with duplicate values.
  • Create second empty ArrayList.
  • Traverse first ArrayList and for each element check if it is present in second ArrayList using contains() method. If not present then add element to second ArrayList.
  • The second ArrayList will be the result with no duplicates.
import java.util.ArrayList;
import java.util.Arrays;

public class ArrayListRemoveDuplicate {

	public static void main(String[] args) {
		
        ArrayList<Integer> list = new ArrayList<>(Arrays .asList(1, 2, 2, 5, 10, 21, 5, 3, 8, 9, 0, 3)); 
  
        System.out.println("ArrayList with duplicates: " + list); 
   
        ArrayList<Integer> secondList = removeDuplicates(list); 
   
        System.out.println("ArrayList with duplicates removed: " + secondList); 
	}
	
	//Function to remove duplicates  
    public static <T> ArrayList<T> removeDuplicates(ArrayList<T> list) { 
        // Create a new ArrayList 
        ArrayList<T> newList = new ArrayList<T>(); 
  
        // Traverse through the list with duplicates 
        for (T element : list) { 
        	// If this element is not present in secondList then add it 
            if (!newList.contains(element)) { 
                newList.add(element); 
            } 
        }  
        return newList; 
    } 
}

Approach 2 – LinkedHashSet

  • Get first ArrayList with duplicate values.
  • Create a LinkedHashSet from this ArrayList. In LinkedHashSet duplicates will be removed.
  • Convert LinkedHashSet to ArrayList.

We have used LinkedHashSet because it maintains insertion order.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.Set;

public class ArrayListRemoveDuplicate {

	public static void main(String[] args) {
		
        ArrayList<Integer> list = new ArrayList<>(Arrays .asList(1, 2, 2, 5, 10, 21, 5, 3, 8, 9, 0, 3)); 
  
        System.out.println("ArrayList with duplicates: " + list); 
   
        ArrayList<Integer> secondList = removeDuplicates(list); 
   
        System.out.println("ArrayList with duplicates removed: " + secondList); 
	}
	
	  //Function to remove duplicates from an ArrayList 
    public static <T> ArrayList<T> removeDuplicates(ArrayList<T> list) { 
        // Create a new LinkedHashSet from ArrayList
        Set<T> set = new LinkedHashSet<>(list); 
        
        //create list from Set
        list = new ArrayList(set);
        
        return list; 
    } 
}