Removing Duplicates from an ArrayList in Java

Comments · 1 Views

There are multiple ways to remove duplicate elements from an ArrayList in Java. Below are s

ArrayLists are a commonly used data structure in Java for storing dynamic collections of elements. However, they allow duplicate values, which can sometimes be undesirable. In this article, we will explore different methods to remove duplicate arraylist remove duplicates.

Methods to Remove Duplicates

1. Using a HashSet

The HashSet data structure does not allow duplicate values, making it an efficient way to remove duplicates from an ArrayList.
import java.util.*;

public class RemoveDuplicates {
public static void main(String[] args) {
List<String> list = new ArrayList<>(Arrays.asList("apple", "banana", "apple", "orange", "banana"));

Set<String> set = new HashSet<>(list);
List<String> uniqueList = new ArrayList<>(set);

System.out.println(uniqueList);
}
}
Explanation: This method converts the ArrayList into a HashSet, which automatically removes duplicates. Then, it converts the set back into a list.

2. Using LinkedHashSet

If maintaining the insertion order is important, a LinkedHashSet can be used instead of a HashSet.
Set<String> set = new LinkedHashSet<>(list);
List<String> uniqueList = new ArrayList<>(set);
Benefit: This approach preserves the order of the original list while removing duplicates.

3. Using Streams (Java 8+)

With Java 8, the Stream API provides a concise way to remove duplicates.
List<String> uniqueList = list.stream()
.distinct()
.collect(Collectors.toList());
Explanation: The distinct() method filters out duplicate values while preserving order.

4. Using Iteration

For scenarios where specific conditions dictate duplicate removal, a manual approach using iteration may be necessary.
List<String> uniqueList = new ArrayList<>();
for (String item : list) {
if (!uniqueList.contains(item)) {
uniqueList.add(item);
}
}
Drawback: This method has a higher time complexity of O(n²) and is less efficient for large lists.

Conclusion

Removing duplicates from an ArrayList is essential when unique elements are required. The best method depends on your use case:

Use HashSet for fast removal without preserving order.

Use LinkedHashSet to retain insertion order.

Use Streams for concise and efficient operations.

Use iteration when additional logic is needed

Comments