Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,845 questions

51,766 answers

573 users

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 170 views
2 answers 80 views
1 answer 68 views
2 answers 168 views
1 answer 57 views
...