Java - Queue example

Posted on October 25, 2016


Queue is sub interface of Collection interface which provide addtion insertion, extraction and inspection operation. Queues typically order the elements in FIFO (first-in-first -out) manner. The LinkedList and the PriorityQueue are the implementation of queue in the JavaCollection API.

The basic operations of queue are

  • offer() and add() - Insert an element at the tail of the queue.
  • poll() and remove() - Remove an element from the head of queue.
  • peek()  and element() - Return an element from the head of queue.

Methods add() ,remove()  and element()  throw exception if any condition fails.

Methods offer(), poll() and peek()  return special value (either null or false, depending on the operation) if any condition fails. 

QueueExample.java

package com.boraji.tutorial;

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

/**
 * @author imssbora
 *
 */
public class QueueExample {
	public static void main(String[] args) {
		Queue<String> queue=new LinkedList<>();
		
		/*Add elements to queue*/
		queue.offer("One");
		queue.offer("Two");
		queue.offer("Three");
		queue.offer("Four");
		queue.offer("Five");
		
		System.out.println("Elements in queue: "+queue);
		
		/*Remove element from the queue*/
		String removeEle=queue.poll();
		System.out.println("Removed element: "+removeEle);
		System.out.println("Elements in queue after poll: "+queue);
		
		/*Get first element from the queue*/
		String element=queue.peek();
		System.out.println("Returned element: "+element);
		System.out.println("Elements in queue after peek: "+queue);
		
	}
}

Output

Elements in queue: [One, Two, Three, Four, Five]
Removed element: One
Elements in queue after poll: [Two, Three, Four, Five]
Returned element: Two
Elements in queue after peek: [Two, Three, Four, Five]