Collection : Queue Example


 

Collection : Queue Example

In this tutorial we will describe implementation of Queue with example.

In this tutorial we will describe implementation of Queue with example.

Collection : Queue Example

In this tutorial we will describe implementation of Queue with example.

Queue :

A java.util.Queue interface is type of collection which holds elements for processing. It shows an ordered list of object as List.
It is based on concept of FIFO(First In First Out). Queue contains additional operations of insertion deletion and displaying which are - offer(Object o), poll(), peek().

Methods of Queue : Following are some methods of queue -

offer(Object o) :  It is of Boolean type and works like add(o) method of Collection and inserts the specified element into your queue.
It returns true if addition of element is possible else returns false.

poll() : It retrieves the head of queue and remove from the queue. It returns null is queue is empty.

remove() : It retrieves the head of queue and remove from the queue. The difference from the poll() method is that it returns an exception of NoSuchElementException in place of null if queue is empty.

peek() : This method retrieves the head of the queue without removing that. It returns null if queue is empty.

element() : This method retrieves the head of the queue without removing that. The difference from the poll() method is that it returns an exception of NoSuchElementException in place of null if queue is empty.

Example :

package collection;

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

class QueueExample{
public static void main(String[] args){
//Creating queue
Queue<Integer> queue=new LinkedList<Integer>();

//Adding elements to the queue
queue.offer(22);
queue.offer(44);
queue.add(77);
queue.add(11);
System.out.println("Size of queue : "+queue.size());
System.out.println("Queue elements : "+queue);

//Removing element
queue.poll();
queue.remove();
System.out.println("Size of queue : "+queue.size());
System.out.println("Queue elements : "+queue);
System.out.println("Queue header element : "+queue.peek());
}
}

Description : In this example we are implementing queue for Integer. Queue is interface so we are creating its object using LinkedList as -
Queue<Integer> queue=new LinkedList<Integer>();
For adding element we are using offer() and add() methods. Next calculating size of queue and displaying elements of queue.
For removing element from the queue you can use remove() method or poll() method.. Here peek() method returns the top element of queue.

Output :

Size of queue : 4
Queue elements : [22, 44, 77, 11]
Size of queue : 2
Queue elements : [77, 11]
Queue header element : 77

Ads