
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find If an Element is in Stack in Java
A stack is a linear data structure where elements are stored in the LIFO manner. Here, LIFO stands for Last In First Out which means the last element inserted would be the first element to be accessed.
In Java, stack is a class provided by the Java collection framework and it implements the Stack data structure. In this article we will write Java program to find if an element is in stack or not.
Using Stack.search() Method
The method java.util.Stack.search() is used to find if an element is in the stack or not in Java. This method takes a single parameter i.e. the element that is searched in the stack. It returns the position of the element in the stack(counting from one) if it is available and returns -1 if the element is not available in the stack.
Example
A program that demonstrates this is given as follows ?
import java.util.Stack; public class Demo { public static void main (String args[]) { Stack<String> stack = new Stack<>(); stack.push("Apple"); stack.push("Mango"); stack.push("Pear"); stack.push("Orange"); stack.push("Guava"); System.out.println("The stack elements are: " + stack); System.out.println("The element Mango is in the stack at position: " + stack.search("Mango")); System.out.println("The element Peach is in the stack at position: " + stack.search("Peach")); } }
On executing the above code, following output will be displayed ?
The stack elements are: [Apple, Mango, Pear, Orange, Guava] The element Mango is in the stack at position: 4 The element Peach is in the stack at position: -1
By Iterating through Stack
Another way to find an element is by iterating through the stack. In this way, we iterate and check each element using for-each loop until this loop finds the match.
Example
Following Java program shows the implementation of above approach.
import java.util.Stack; public class Demo { public static void main(String[] args) { Stack<Integer> stack = new Stack<>(); stack.push(101); stack.push(201); stack.push(301); stack.push(302); stack.push(303); System.out.println("The stack elements are: " + stack); // element to find int findElmnt = 201; boolean found = false; // for-each loop to check for(int i : stack) { if(i == findElmnt) { found = true; break; } } // printing the result if(found) { System.out.println("Element is in the Stack"); } else { System.out.println("Element is not in the Stack"); } } }
On running, you will get the following output ?
The stack elements are: [101, 201, 301, 302, 303] Element is in the Stack