How to remove duplicates from arraylist in java

Let’s learn how to remove duplicates from arraylist in java.

How to remove duplicates from arraylist in java

Here the task is to remove duplicates from arraylist.

import java.util.ArrayList;
import java.util.Arrays;
public class DuplicatesFromArraylist
{
   public static <T> ArrayList<T> removeDuplicate(ArrayList<T> al)
   {
      ArrayList<T> alNew = new ArrayList<T>();
      for(T element : al)
      {
         // if element is present in alNew then add it
         if(!alNew.contains(element))
         {
            alNew.add(element);
         }
      }
      // return alNew
      return alNew;
   }
   public static void main(String[] args)
   {
      ArrayList<Integer> al = new ArrayList<>(Arrays.asList(2, 2, 4, 4, 6, 6, 8, 8, 1, 3, 5, 7, 9));
      System.out.println("Before removing duplicates from ArrayList: " + al);
      ArrayList<Integer> alNew = removeDuplicate(al);
      // printing ArrayList with duplicates
      System.out.println("After removing duplicates from ArrayList: " + alNew);
   }
}


Output:

Before removing duplicates from ArrayList: [2, 2, 4, 4, 6, 6, 8, 8, 1, 3, 5, 7, 9]
After removing duplicates from ArrayList: [2, 4, 6, 8, 1, 3, 5, 7, 9]


remove duplicates from array java 8

To remove duplicates from array in java 8 use distinct() method.

distinct() method returns a stream consisting of the distinct elements (according to Object.equals(Object)) of given stream.

Let’s see an example.

import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class RemoveDuplicatesJava8
{
   public static void main(String[] args)
   {
      List li1 = new ArrayList<>(Arrays.asList(2, 2, 4, 4, 6, 6, 8, 8, 1, 3, 5, 7, 9));
      System.out.println("Before removing duplicate elements: " + li1);
      // create new list from elements of original list
      List li2 = li1.stream().distinct().collect(Collectors.toList());
      // printing ArrayList with duplicates removed
      System.out.println("After removing duplicate elements: " + li2);
   }
}


Output:

ArrayList with duplicates: [2, 2, 4, 4, 6, 6, 8, 8, 1, 3, 5, 7, 9]
ArrayList with duplicates removed: [2, 4, 6, 8, 1, 3, 5, 7, 9]