English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this example, we will learn how to remove duplicate elements from an ArrayList using Java.
To understand this example, you should be familiar with the followingJava programmingTopic:
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 an array //Using the 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 to a set Set<Integer> set = new LinkedHashSet<>(); set.addAll(numbers); //Delete all elements from the arraylist numbers.clear(); //Add elements from the set collection to the arraylist numbers.addAll(set); System.out.println("ArrayList without duplicates: ") + numbers); } }
Output Result
ArrayList with duplicates: [1, 2, 3, 4, 1, 3] ArrayList without duplicates: [1, 2, 3, 4]
In the above example, we created an arraylist named numbers. The arraylist contains duplicate elements.
To remove duplicate elements from the arraylist, we need:
Add all elements from the arraylist to the set collection
Use the clear() method to clear the arraylist
Then add all elements from the set collection to the arraylist
Here, we use LinkedHashSet to create a collection. This is because it removes duplicate elements while maintaining the insertion order. For more information, please visitJava LinkedHashSet.
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 an array //Using the asList() method of the Array 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 an array list Stream<Integer> stream = numbers.stream(); //Invoke the Stream's distinct() //Remove duplicate elements stream = stream.distinct(); //Convert the stream to an arraylist numbers = (ArrayList<Integer>)stream.collect(Collectors.toList()); System.out.println("ArrayList without duplicates: ") + numbers); } }
Output Result
ArrayList with duplicates: [1, 2, 3, 4, 1, 3] ArrayList without duplicates: [1, 2, 3, 4]
In the above example, we created an arraylist named numbers. The arraylist contains duplicate elements.
Here, we useStreamThe class removes duplicate elements from the arraylist.
Numbers.stream() - Create a stream from arraylist
stream.distinct() - Remove duplicate elements
stream.collect(Collectors.toList()) - Return list from stream
Here, we use type conversion to convert the returned list to an arraylist.