Algorithm


  1. Create an ArrayList to store the unique elements.
  2. Create a HashSet to keep track of the elements that have already been added to the new ArrayList.
  3. Iterate through the original ArrayList.
  4. For each element, check if it exists in the HashSet.
    • If it does not exist, add it to the new ArrayList and the HashSet.
    • If it already exists, skip it.
  5. The new ArrayList now contains only unique elements.

 

Code Examples

#1 Code Example- Remove duplicate elements from ArrayList using Set

Code - Java Programming

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

class Main {
  public static void main(String[] args) {

    // create an arraylist from the array
    // using asList() method of the Arrays class
    ArrayList < Integer> numbers = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 1, 3));
    System.out.println("ArrayList with duplicate elements: " + numbers);

    // convert the arraylist into a set
    Set < Integer> set = new LinkedHashSet<>();
    set.addAll(numbers);

    // delete al elements of arraylist
    numbers.clear();

    // add element from set to arraylist
    numbers.addAll(set);
    System.out.println("ArrayList without duplicate elements: " + numbers);
  }
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
ArrayList with duplicate elements: [1, 2, 3, 4, 1, 3]
ArrayList without duplicate elements: [1, 2, 3, 4]

#2 Code Example- Remove duplicate elements from ArrayList using Stream

Code - Java Programming

import java.util.ArrayList;
import java.util.Arrays;
import java.util.stream.Collectors;
import java.util.stream.Stream;

class Main {
  public static void main(String[] args) {

    // create an arraylist from the array
    // using asList() method of the Arrays class
    ArrayList < Integer> numbers = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 1, 3));
    System.out.println("ArrayList with duplicate elements: " + numbers);

    // create a stream from arraylist
    Stream < Integer> stream = numbers.stream();

    // call the distinct() of Stream
    // to remove duplicate elements
    stream = stream.distinct();

    // convert the stream to arraylist
    numbers = (ArrayList < Integer>)stream.collect(Collectors.toList());
    System.out.println("ArrayList without duplicate elements: " + numbers);

  }
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
ArrayList with duplicate elements: [1, 2, 3, 4, 1, 3]
ArrayList without duplicate elements: [1, 2, 3, 4]
Advertisements

Demonstration


Java Programing Example to Remove duplicate elements from ArrayList-DevsEnv