Data Structures & Algorithms

Set: Remove Duplicates

neal89 2025. 2. 25. 09:57

📌 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

  1. Create a HashSet and add all elements from myList.
    • This automatically removes duplicates.
  2. Convert the HashSet back to a List using new ArrayList<>(set).
  3. 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.