📌 Problem Statement
You are given a list of integers, myList, where some elements may be repeated.
Your task is to remove all duplicate elements and return a new list containing only the unique elements.
✏️ Method Signature:
public static List<Integer> removeDuplicates(List<Integer> myList);
🔹 Example Input & Output
Input: [1, 2, 2, 3, 4, 4, 5]
Output: [1, 2, 3, 4, 5]
🛠 Solution Approach
We can solve this problem efficiently using Java’s HashSet:
- A HashSet automatically removes duplicate elements, as it does not allow duplicates.
- Time Complexity: O(N), since adding elements to a HashSet takes O(1), and converting it to a List is O(N).
- Space Complexity: O(N), as we store the unique elements in a HashSet.
✅ Java Solution
import java.util.*;
public class RemoveDuplicatesExample {
public static List<Integer> removeDuplicates(List<Integer> myList) {
// Use HashSet to remove duplicates
Set<Integer> uniqueSet = new HashSet<>(myList);
// Convert back to a List and return
return new ArrayList<>(uniqueSet);
}
public static void main(String[] args) {
List<Integer> myList = Arrays.asList(1, 2, 2, 3, 4, 4, 5);
List<Integer> uniqueList = removeDuplicates(myList);
System.out.println("Unique List: " + uniqueList);
}
}
📝 Explanation
- Create a HashSet and add all elements from myList.
- This automatically removes duplicates.
- Convert the HashSet back to a List using new ArrayList<>(set).
- Return the new unique list.
🚀 Alternative Approach: Using Streams (Java 8+)
If you prefer a one-liner functional approach, you can use Java Streams:
import java.util.*;
import java.util.stream.Collectors;
public class RemoveDuplicatesStream {
public static List<Integer> removeDuplicates(List<Integer> myList) {
return myList.stream().distinct().collect(Collectors.toList());
}
public static void main(String[] args) {
List<Integer> myList = Arrays.asList(1, 2, 2, 3, 4, 4, 5);
System.out.println("Unique List: " + removeDuplicates(myList));
}
}
🔹 Pros of Using Streams
✔ More readable
✔ No additional data structures
✔ Functional programming style
🎯 Key Takeaways
- Use HashSet for efficient duplicate removal (O(N) time complexity).
- Convert the Set back to a List when needed.
- For Java 8+, use Streams for a more concise solution.
'Data Structures & Algorithms' 카테고리의 다른 글
Priority Queue (Heap): Implement a Task Scheduler (Comparable & Comparator) (0) | 2025.02.27 |
---|---|
Graph: Check if a Path Exists in an Undirected Graph (0) | 2025.02.26 |
HT: Finding Common Elements (0) | 2025.02.25 |
Stack: Parentheses Balanced (0) | 2025.02.23 |
Stack: Reverse a String (0) | 2025.02.22 |