Problem Statement: Write a Java program to remove duplicates from an ArrayList while preserving the original order.
Here’s a Java program that demonstrates how to remove duplicates from an ArrayList
while preserving the original order. I’ll provide an explanation of the program’s logic.
package com.javacodepoint.collection;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
public class RemoveDuplicatesPreserveOrderDemo {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
numbers.add(20);
numbers.add(40);
numbers.add(10);
System.out.println("Original List: " + numbers);
// Removing duplicates while preserving order
List<Integer> uniqueNumbers = removeDuplicatesPreserveOrder(numbers);
System.out.println("List after removing duplicates: " + uniqueNumbers);
}
// Method to remove duplicates while preserving order
public static <T> List<T> removeDuplicatesPreserveOrder(List<T> list) {
HashSet<T> seen = new LinkedHashSet<>();
List<T> uniqueList = new ArrayList<>();
for (T element : list) {
if (seen.add(element)) {
uniqueList.add(element);
}
}
return uniqueList;
}
}
OUTPUT:
Original List: [10, 20, 30, 20, 40, 10]
List after removing duplicates: [10, 20, 30, 40]
Explanation:
- Creating the List: We create an
ArrayList
namednumbers
and populate it with some integers, including duplicates. - Printing the Original List: We print the contents of the
numbers
list usingSystem.out.println()
. - Removing Duplicates while Preserving Order: We call the
removeDuplicatesPreserveOrder()
method to remove duplicates from thenumbers
list while preserving the original order. removeDuplicatesPreserveOrder()
Method: This method uses two data structures to achieve the goal. It uses aHashSet
(seen
) to keep track of elements that have been seen, and a newArrayList
(uniqueList
) to store the unique elements in the order they appear.- Iterating Through the List: We iterate through the
list
using a enhancedfor
loop. For each element, we check if it’s not already in theseen
set (meaning it’s unique). If it’s unique, we add it to both theseen
set and theuniqueList
. - Returning the List without Duplicates: The method returns the
uniqueList
, which contains the elements from the input list without duplicates, while preserving the original order.
By using a HashSet
to keep track of seen elements and an ArrayList
to store unique elements in order, the program effectively removes duplicates from the ArrayList
while maintaining the original element order.
See also: Create a stack using an ArrayList.