How to Prevent the Addition of Duplicate Elements to the Java ArrayList?
Ever wondered how you can make an ArrayList unique? Well, in this article we’ll be seeing how to prevent the addition of duplicates into our ArrayList. If an ArrayList have three duplicate elements, but at the end, only the ones which are unique are taken into the ArrayList and the repetitions are neglected can be done using various approaches discussed as below.
Example:
Input : [1, 1, 2, 2, 3, 3, 4, 5, 8]
Output: [1, 2, 3, 4, 5, 8]
Input : [1, 1, 1, 1, 1, 1, 1, 1, 1]
Output: [1]
Approach 1: contains() method
- Add elements one by one.
- Check for their presence using the contains method.
- Ignore the current element if it returns true.
- Else add the element.
Below is the implementation of the above approach:
Java
import java.util.ArrayList;
class GFG {
public static void main(String[] args)
{
int array[] = { 1 , 1 , 2 , 2 , 3 , 3 , 4 , 5 , 8 };
ArrayList<Integer> ans = new ArrayList<>();
for ( int i : array) {
if (!ans.contains(i)) {
ans.add(i);
}
}
for ( int i : ans) {
System.out.print(i + " " );
}
}
}
|
Time Complexity: O(N2), as contains method can traverse through the entire array in the worst case.
Space Complexity: O(1), as no extra space is used.
Approach 2: HashSet
- Add elements one by one.
- Check for their presence using HashSet.
- Ignore the current element if it returns true.
- Else add the element.
Below is the implementation of the above approach:
Java
import java.util.ArrayList;
import java.util.HashSet;
class GFG {
public static void main(String[] args)
{
int array[] = { 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 };
ArrayList<Integer> ans = new ArrayList<>();
HashSet<Integer> set = new HashSet<>();
for ( int i : array) {
if (!set.contains(i)) {
ans.add(i);
set.add(i);
}
}
for ( int i : ans) {
System.out.print(i + " " );
}
}
}
|
Time Complexity: O(n)
Space Complexity: O(n), as a HashSet is used to store the traversed elements.
Last Updated :
11 Dec, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...