Java – Queue Example

Queue interface is in java.util package of java. Queue works like first in first out (FIFO) policy. Queue does not require any fix dimension like String array and int array. Queue contains many useful methods. To add element in Queue, we can use add() method of Queue interface.

To get value from Queue, Queue provides poll() and peek() method and Queue size() method. Size() method returns total number of elements in Queue. peek() method looks at the object at the head of this Queue without removing it from the Queue

Queue Example

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

public class QueueExample {

    public static void main(String[] args) {

        Queue<String> qe=new LinkedList<String>();

        qe.add("b");
        qe.add("a");
        qe.add("c");
        qe.add("e");
        qe.add("d");

        Iterator it=qe.iterator();

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

        while(it.hasNext())
        {
            String iteratorValue=(String)it.next();
            System.out.println("Queue Next Value :"+iteratorValue);
        }

        // get value and does not remove element from queue
        System.out.println("Queue peek :"+qe.peek());

        // get first value and remove that object from queue
        System.out.println("Queue poll :"+qe.poll());

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

Output

Initial Size of Queue :5
Queue Next Value :b
Queue Next Value :a
Queue Next Value :c
Queue Next Value :e
Queue Next Value :d
Queue peek :b
Queue poll :b
Final Size of Queue :4

Tags:

Bookmark  

 

3 Responses to “Java – Queue Example”

  1. gr says:

    where is the implementation of the poll() and peek() methods?

  2. gr says:

    I got it now, the implementation is in the imported package: import java.util.Queue;

  3. Don Bosco Antony says:

    peek()
    Retrieves, but does not remove, the head (first element) of this list

    poll()
    Retrieves and removes the head (first element) of this list.

Leave a Reply

Security Code:

 

  Random Post