Queue Interface

Queue is an ordered list of objects which is limited to inserting elements at the end of list and deleting elements from the start of list as it follows FIFO principle. Below are few methods declared in the Queue interface. They are as follows:

Method Role
public boolean add(object) Add the given object into the queue.
public Object remove() Removes the head element from the queue.
public Object poll() Retrieves and removes the head of the queue, or returns null if this queue is empty.
public Object peek() Retrieve the head of queue without removing it. Returns null if queue is empty.
public Object element() It is similar to peek(). If queue is empty it throws NoSuchElementException.

Let us see an example:

package collectionInterfaces;

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

public class QueueTest {

  public static void main(String[] args) {
    Queue queue = new LinkedList<>();
    queue.add("test element 1"); 
    queue.add("test element 2"); 
    queue.add("test element 3"); 
    queue.add("test element 4"); 

    System.out.println("Queue elements are " + queue);

    // Peek method returns the head element without removing it from deque
    System.out.println("Peek element -> " + queue.peek());
    System.out.println("After peek queue element(s): " + queue);
    
    // Remove method remove head of the queue.
      String removeElement = (String) queue.remove();
      System.out.println("removed element-" + removeElement);
      System.out.println("After remove deque queue(s): " + queue);
  }
}

Output:

Queue elements are [test element 1, test element 2, test element 3, test element 4]
Peek element -> test element 1
After peek queue element(s): [test element 1, test element 2, test element 3, test element 4]
removed element-test element 1
After remove deque queue(s): [test element 2, test element 3, test element 4]