How to remove duplicates from a stack in Java

1 Answer

0 votes
import java.util.HashSet;
import java.util.Random;
import java.util.Stack;
import java.util.Set;
 
public class StackRemoveDuplicates {
     public static Stack<Integer> removeDuplicatesFromStack(Stack<Integer> stack) {
        Set<Integer> seen = new HashSet<>();
        Stack<Integer> uniqueStack = new Stack<>();
 
        while (!stack.isEmpty()) {
            int element = stack.pop();
            if (!seen.contains(element)) {
                seen.add(element);
                uniqueStack.push(element);
            }
        }
 
        return uniqueStack;
    }
    private static Stack<Integer> initStack(Long size, int bound) {
        Stack<Integer> stack = new Stack<>();
        Random random = new Random();
         
        for (int i = 0; i < size; i++) {
            stack.add(random.nextInt(bound) + 1);
        }
         
        return stack;
    }
    public static void main(String[] args) {
        Stack<Integer> stack = initStack(15L, 10);
         
        System.out.println("Random Elements: " + stack);
        System.out.println("Remove Duplicates: " + removeDuplicatesFromStack(stack));
    }
}
 
 
 
/*
run:
 
Random Elements: [9, 5, 6, 9, 6, 9, 8, 5, 7, 8, 8, 8, 3, 3, 2]
Remove Duplicates: [2, 3, 8, 7, 5, 9, 6]
 
*/

 



answered Oct 11, 2025 by avibootz
edited Oct 11, 2025 by avibootz

Related questions

3 answers 195 views
2 answers 100 views
1 answer 80 views
2 answers 194 views
1 answer 67 views
...