Way2Java

Queue Offer Poll Peek Remove Elements Java

Note: Before going into the details of this "Queue Offer Poll Peek Remove Elements Java", it is advised to go through Queue Fundamentals where queue basics were discussed.

Following are some methods that do the similar operations.

offer() method is equivalent to add() method of Collection interface.

Example on Queue Offer Poll Peek Remove Elements Java
import java.util.*;
public class QueueExample
{
  public static void main(String args[])
  {
    Queue countries = new LinkedList();
    					   
    countries.add("India");
    countries.add("USA");
    countries.offer("UK");
    countries.offer("Canada");
    System.out.print("Queue elements with iterrator: ");      
    Iterator it1 = countries.iterator();

    while(it1.hasNext())
    {
      System.out.print(it1.next() + " ");
    }    
   
    System.out.println("\npoll(): " + countries.poll());
    System.out.println("peek(): " + countries.peek());
    System.out.println("element(): " + countries.element());
    System.out.println("remove(): " + countries.remove());
    System.out.println("\npoll(): " + countries.poll());
  }
}



Output Screenshot on Queue Offer Poll Peek Remove Elements Java

Queue countries = new LinkedList();

Queue, being an interface, its object directly cannot be created directly. Any one of its subclass objects can be assigned to Queue reference. This is what happened in the above statement. LinkedList is a subclass of Queue and its object is assigned to countries of Queue interface. For all practical purposes countries works as an object.

countries.add(“India”);
countries.offer(“UK”);

With add() method inherited from Collection and with offer() method defined in Queue, elements are added to queue countries.

System.out.println(“\npoll(): ” + countries.poll());
System.out.println(“peek(): ” + countries.peek());
System.out.println(“element(): ” + countries.element());
System.out.println(“remove(): ” + countries.remove());
System.out.println(“\npoll(): ” + countries.poll());

The poll() method returns India, the first element added and deletes it. The peek() method returns the element but does not deletes. For this reason, peek, element and remove prints the same, USA. After calling remove, the poll() prints UK as remove() method deleted USA.

A generic queue that stores strings can be created as follows.

Queue countries = new LinkedList();

Now the queue countries stores only strings.