Queue in java

In this section we will discuss about queue in java. Queue is a interface in java.util package of java.

Queue in java

In this section we will discuss about queue in java. Queue is a interface in java.util package of java.

Queue in java

Queue in java

In this section we will discuss about queue in java. Queue is a interface in java.util package of java. It holds the collection of data or element and follow the FIFO (first in first out) manner, which means the data which is added first into the queue will be removed first from the queue. Whatever the ordering is, head of the queue is removed first from the queue by calling remove() method. All the new element are inserted at the tail of the queue. The remove() and poll() method of queue, remove and return the head of the queue. remove() and poll() method are same in behavior but remove() will throw an exception when queue is empty and poll() will return null if queue is empty. Some of the methods as follows:

Methods Summary
element()Retrieves but does not remove, the head of the queue
peek()Retrieves but does not remove the head of this queue and return null if the queue is empty
poll()Remove the head of this queue and return null if the queue is empty
remove()Retrieves and remove the head of this queue.

Example : A Program to implement  queue

import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;
public class QueueDemo 
 {
   public static void main(String[] args) {
        Queue qe=new LinkedList();

        qe.add("Welcome");
        qe.add("To");
        qe.add("Rose");
        qe.add("India");
        Iterator it=qe.iterator();

        System.out.println("Initial Capacity of Queue :"+qe.size());

        while(it.hasNext())
        {
            String iteratorValue=(String)it.next();
           
        }//retrieves but does not remove from the queue
         System.out.println("peek method:"+qe.peek());
        // get first value and remove that object from queue
        System.out.println("poll method:"+qe.poll());

        System.out.println("Final Size of Queue :"+qe.size());
    }
}

Description : In the above example we have implemented queue with subclass LinkedList and with use of peek(), poll()  method retrieving and removing the element from the queue.

Output : After compiling and executing the above program

Download SourceCode