Learnitweb

Stack in Java

1. Introduction

Stack is a last-in-first-out (LIFO) stack of objects. Stack class is a part of collection framework. Elements can in inserted and retrieved at only one end of the Stack. Stack in Java is represented by java.util.Stack class. The java.util.Stack class extends java.util.Vector. Stack implements following interfaces:

  • Serializable
  • Cloneable
  • Iterable<E>
  • Collection<E>
  • List<E>
  • RandomAccess

A stack of plates in a cupboard is a real life example of Stack. The last plate put at the top of stack is taken out first for use.

Stack in Java

By default, there are no items in Stack, i.e. when first created, it contains no items. Stack only provides few basic operations whereas Deque interface provides more complete and consistent set of LIFO stack operations and should be preferred whenever LIFO collection is required.

2. Constructor

Stack(): The constructor creates an empty stack.

Stack stack = new Stack();

You can use generics with Stack:

Stack<String> stack = new Stack();

3. Methods of Stack

3.1 push()

E push(E item): Pushes an item onto the top of the stack.

stack.push("one");
stack.push("two");
stack.push("three");

3.2 pop()

E pop(): Removes the object at the top of the stack and returns that object.

stack.pop();

3.3 peek()

E peek(): Returns the object at the top of this stack without removing it from the stack.

stack.peek()

3.4 empty()

boolean empty(): Returns true if the stack is empty else returns false.

stack.empty();

int search(Object o): Returns 1 based index of found element else returns -1. The index starts with the top with value 1 i.e. top has index of 1, second element from the top has index of 2 and so on.

stack.search("one");

4. Iterating a Stack

You can use the Iterator to iterate a Stack just like any other collection.

		Iterator<String> itr = stack.iterator();
		while (itr.hasNext()) {
			String element = itr.next();
			System.out.println(element);
		}

Lambda function introduced in Java 8 can also be used to iterate a Stack:

stack.stream().forEach(System.out::println);

5. Example

import java.util.Iterator;
import java.util.Stack;

public class StackExample {
	public static void main(String[] args) {
		Stack<String> stack = new Stack();

		// push three elements in the stack
		stack.push("one");
		stack.push("two");
		stack.push("three");

		System.out.println(stack); // [one, two, three]

		// pop one element from the top
		stack.pop();

		System.out.println(stack); // [one, two]

		// check top element
		String topElement = stack.peek();
		System.out.println(topElement); // two

		// search element "one" in stack
		int result = stack.search("two");
		System.out.println(result); // 1

		// iterating a stack
		Iterator<String> itr = stack.iterator();
		while (itr.hasNext()) {
			String element = itr.next();
			System.out.println(element);
		}

		// iterating a stack using lambda function
		stack.stream().forEach(System.out::println);
	}
}