As arraylist can contains duplicates element, so sometime there would be some requirement to remove the duplicate element from the list.

For Example: { 10, 12, 23, 10, 2, 21, 78, 90, 12 } after removal it should like

{ 10, 12, 23, 2, 21, 78, 90 }

We would use three approach here to remove the duplicates from the list.

First Approach:

Using streams and their distinct method.

Code

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class RemoveDuplicate {
   public static void main(String[] args) {
	   
	   List<Integer> nums = new ArrayList<Integer>();
	   nums.add(10);
	   nums.add(12);
	   nums.add(6);
	   nums.add(8);
	   nums.add(12);
	   nums.add(6);
	   
	   System.out.println("Array with duplicates: " + nums);

	   List<Integer> numsUnique = nums.stream().distinct().collect(Collectors.toList());
	   System.out.println("Array without duplicates: " + numsUnique);   
	
	   
   }
}

Second Approach:

Define an another array list that will store the unique number only.

Code

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class RemoveDuplicate {
   public static void main(String[] args) {
	   
	   List<Integer> nums = new ArrayList<Integer>();
	   nums.add(10);
	   nums.add(12);
	   nums.add(6);
	   nums.add(8);
	   nums.add(12);
	   nums.add(6);
	   
	   System.out.println("Array with duplicates: " + nums);

	 
	   List<Integer> numsUnique = new ArrayList<Integer>();
	   for(Integer num : nums) {
		   if(numsUnique.indexOf(num) == -1) {
			   numsUnique.add(num);
		   }
	   }	   
	   System.out.println("Array without duplicates: " + numsUnique);   
	   
   }
}

Third Approach:

Define a new hashSet, that will store only unique data.

public class RemoveDuplicate {
   public static void main(String[] args) {
	   
	   List<Integer> nums = new ArrayList<Integer>();
	   nums.add(10);
	   nums.add(12);
	   nums.add(6);
	   nums.add(8);
	   nums.add(12);
	   nums.add(6);
	   
	   System.out.println(nums);	   
 
	   Set<Integer> numsUnique = new HashSet<Integer>();
	   for(Integer num : nums) {
		   numsUnique.add(num); 
	   }	
	   System.out.println(numsUnique);
	   
   }
}

Similar Posts