Showing posts with label Collections. Show all posts
Showing posts with label Collections. Show all posts

Thursday, June 28, 2012

Stack Example in Java


Stack is a collection to store data and follows the LIFO (Last In First Out) to remove the elements from it. Following is the implementation of Stack in java.

import java.util.Stack;

public class StackDemo {
      public static void main(String[] args) {       
            Stack<String> stack = new Stack<String>();
            for(int i=0; i<10; i++){
                  stack.push(String.valueOf((i*7)%10));
            }
            System.out.print("\nElements present in Stack (Last In First Out): ");
            for(String str: stack){
                  System.out.print(str + " ");
            }
            System.out.print("\nRemoving Elements from Stack (Last In First Out):");
            while(!stack.isEmpty()){
                  System.out.print(stack.pop() + " ");
            }
      }
}

Queue Example in Java


Queue is a collection to store the data and follows the FIFO (First In First Out) pattern to remove the elements from it. Following is the implementation of Queue in java.

import java.util.LinkedList;
import java.util.Queue;

public class QueueDemo {
      public static void main(String[] args) {
            Queue<String> queue = new LinkedList<String>();
            for(int i=0; i<10; i++){
                  queue.offer(String.valueOf((i*7)%10));
            }
            System.out.print("\nElements present in Queue (First In First Out): ");
            for(String str: queue){
                  System.out.print(str + " ");
            }
            System.out.print("\nRemoving Elements from Queue (First In First Out):");
            while(!queue.isEmpty()){
                  System.out.print(queue.poll() + " ");
            }
      }
}