Home » Java Tutorial » Queue Interface in Java

Queue Interface in Java




Java Java Queue

Queue Interface in Java

Queue interface in Java belongs to the java.util package and is part of the Collection interface. It implements the First-In-First-Out concept of the queue data structure which means, the elements that we insert first are deleted first. We can consider the queue interface similar to the normal queue that we see outside any booking center or ATM.

In the Java queue, we insert the elements through the rear side and remove them through the front side.

Queue interface in Java

Features of Java Queue

  • It adds elements through the rear side and deletes them through the front
  • Implements the First In First Out (FIFO) concept.
  • Supports all methods of the Collection interface
  • Maintains an ordered collection of elements

Queue hierarchy

Queue interface in Java

Methods of the Queue interface

MethodDescriptionParameter
Boolean add(String e)Adds the specified element to the end of the queuee - the element to be added.
Return value - True
Boolean addAll(Collection c)Adds a collection of specified elements to the queue.c - collection of elements to be added
Return value - true
void clear()Clears all the elements in the queue.
Boolean contains(Object o)Checks if the queue contains the specified elementReturn value - true if the queue contains the element
Boolean containsAll(Collection c)Checks if the queue contains all the elements in the collectionReturn value - true if the queue contains all the elements
Object element()Returns the first element(head) in the queue
Boolean equals(Object o)Compares if the queue contains all the specified elements in the exact orderReturn value - true if object elements match with the queue
Boolean isEmpty()Checks if the queue is empty or notReturn value - true if queue contains no values
Iterator iterator()Retrieves the iterator of queue in sequenceReturn value - Iterator
Boolean offer(Object e)Inserts the element as the taile - element to be added
Object peek()Retrieves the first element of the queue(head)Returns null if the queue is empty
Object poll()Retrieves and removes the first element of the queue(head)Returns null if the queue is empty
Object remove()Removes the first element from the queue
Boolean remove(Object o)Removes the first occurrence of the specified object from the queue if presento - The element that needs to be removed
Return value - true if queue contains the element
Boolean removeAll(Collection c)Removes the first occurrence of all the elements in the collection from the queue if presentc - collection of elements
Return value - true if the queue contains the collection
Boolean retainAll(Collection c)Retains all the elements specified in collection in queue. Other elements will be removedc - collection of elements that has to be retained
Return value - true if the queue changed due to the method called
int size()Fetches the size of the queueReturn value - size of the queue
Spliterator spliterator()Returns a spliterator over the elements in the queue
Object[] toArray()Returns an array of elements in proper sequenceReturn value - Array of all elements in the queue in proper sequence
String toString()Returns a String representation of the elements collectionReturn value - String of array elements separated by comma and space and enclosed within []
READ  PriorityQueue in Java

Classes that implement the Queue interface

Java Queue is an interface and hence it requires implementation classes. There are 3 classes for implementing the Queue interface: PriorityQueue, LinkedList, and ArrayDeque.

PriorityQueue

PriorityQueue is a class that implements the Queue and processes the elements based on the priority using the First-In-First-Out fashion.

import java.util.PriorityQueue;

public class PriorityQueueExample {

  public static void main(String[] args) {
    PriorityQueue<String> p = new PriorityQueue();
    p.add("Akash");
    p.add("Aditya");
    p.add("Ashok");
    
    for(String s : p)
      System.out.println(s);
    System.out.println("First element: " + p.peek());
    
  }

}
Aditya
Akash
Ashok
First element: Aditya

LinkedList

LinkedList is a commonly used queue implementation class that is based on the LinkedList data structure. Each element links to another using the address. Every element is called a node that contains a data part and an address part. It stores data in a linear fashion.

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

public class LinkedListQueue {

  public static void main(String[] args) {
    Queue<String> cities = new LinkedList<String>();
    cities.add("Delhi");
    cities.add("Chennai");
    cities.add("Bangalore");
    
    System.out.println(cities);
    System.out.println(Head element: " + cities.peek());

  }

}
[Delhi, Chennai, Bangalore]
Head element: Delhi

ArrayDeque

The ArrayDeque class implements the Deque interface which means we can insert and delete the elements from both sides. It allows us to create a resizable array without any capacity.

import java.util.ArrayDeque;
import java.util.Deque;

public class ArrayDequeExample {

  public static void main(String[] args) {
    Deque<Integer> d = new ArrayDeque<Integer>();
    d.add(100);
    d.add(200);
    d.add(300);
    d.add(400);
    d.add(500);
    
    System.out.println(d);
    
    System.out.println("Head element: " + d.peek());
    
  }

}
[100, 200, 300, 400, 500]
Head element: 100

Interfaces that extend the Queue interface

The Queue interface also contains subinterfaces that extend it. The list of the subinterfaces is Deque, BlockingQueue, and BlockingDeque.

Deque

Deque means Double-ended queue which means we can insert and delete elements from both ends. The ArrayDeque class implements this interface.

Deque d = new ArrayDeque();

BlockingQueue

The BlockingQueue implementing classes are thread-safe, unlike the Queue classes. The PriorityBlockingQueue, LinkedBlockingQueue, ArrayBlockingQueue are the classes that implement this interface.

READ  HashSet in Java

BlockingDeque

The BlockingDeque interface has a special functionality that can block the insertion operation when the queue is full or block the deletion operation when the queue is empty. Since it is a type of Deque interface, it supports insertion and deletion from both ends.

Example: Add elements to a Queue

Below is an example to add elements to a Queue using add() and addAll() methods. Using the add() method we can add a specific element and using the addAll() method we can add a collection of elements.

import java.util.PriorityQueue;
import java.util.Queue;

public class AddQueueElements {

  public static void main(String[] args) {
    Queue<String> q = new PriorityQueue<String>();
    q.add("Akshay");
    q.add("Tushar");
    q.add("Suraj");
    System.out.println("Elements in queue after add opertion: " + q);
    
    Queue<String> qu = new PriorityQueue<String>();
    qu.add("Bharat");
    qu.add("Chandru");
    
    q.addAll(qu);
    
    System.out.println("Elements in queue after addAll opertion: " + q);
  }

}
Elements in queue after add opertion: [Akshay, Tushar, Suraj]
Elements in queue after addAll opertion: [Akshay, Bharat, Suraj, Tushar, Chandru]

Example: Remove elements from a queue

We can use the remove() method to remove the head element and a specific element if we specify the value. We can remove a collection of elements using the removeAll() method. To retrieve and remove the head element of the queue, we can use the poll method.

import java.util.PriorityQueue;
import java.util.Queue;

public class RemoveQueueElements {

  public static void main(String[] args) {
    Queue<String> q = new PriorityQueue<String>();
    q.add("Akshay");
    q.add("Tushar");
    q.add("Suraj");
    Queue<String> qu = new PriorityQueue<String>();
    qu.add("Bharat");
    qu.add("Chandru");
    qu.add("Kumar");
    
    q.addAll(qu);
    System.out.println("Elements in queue after add opertion: " + q);
    
    q.remove();
    q.remove("Tushar");
    
    System.out.println("Elements in the queue after remove operation: " + q);
    
    q.removeAll(qu);
    
    System.out.println("Elements in the queue after removeAll operation: " + q);
    System.out.println(q.poll());
    
    System.out.println("Is queue empty after poll method: " + q.isEmpty());

  }

}
Elements in queue after add opertion: [Akshay, Bharat, Kumar, Tushar, Chandru, Suraj]
Elements in the queue after remove operation: [Bharat, Chandru, Kumar, Suraj]
Elements in the queue after removeAll operation: [Suraj]
Suraj
Is queue empty after poll method: true

Example: Access elements in a queue

Using the iterator method, we can navigate through all the values in the queue. To retrieve the head element, we can use the peek method. The below example illustrates both the methods.

import java.util.Iterator;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Spliterator;

public class AccessQueueElements {

  public static void main(String[] args) {
    Queue<String> q = new PriorityQueue<String>();
    q.add("Red");
    q.add("Blue");
    q.add("Black");
    q.add("White");
    q.add("Green");
    
    System.out.println("Iterate using the iterator method: ");
    Iterator<String> i = q.iterator();
    while(i.hasNext())
      System.out.println(i.next());
    
    System.out.println("Head element: " + q.peek());
    

  }

}
Iterate using the iterator method: 
Black
Green
Blue
White
Red
Head element: Black

Example: Convert queue to an array

We can also convert queue data structure into an array using the toArray method.

import java.util.Arrays;
import java.util.PriorityQueue;
import java.util.Queue;

public class QueueToArray {

  public static void main(String[] args) {
    Queue<String> q = new PriorityQueue<String>();
    q.add("Red");
    q.add("Blue");
    q.add("Black");
    q.add("White");
    q.add("Green");
    
    String arr[] = q.toArray(new String[q.size()]);
    System.out.println(Arrays.toString(arr));
    
    System.out.println("Value at index 2: " + arr[2]);

  }

}
[Black, Green, Blue, White, Red]
Value at index 2: Blue

 

READ  Enum in Java

Reference

Array Interview Questions
Graph Interview Questions
LinkedList Interview Questions
String Interview Questions
Tree Interview Questions
Core Java Interview Questions

AD Blocker Detected !

Advertisements help running this website for free.

To view the content please disable AdBlocker and refresh the page.

Wait !!!

You can Crack Technical Interviews of Companies like Amazon, Google, LinkedIn, Facebook, PayPal, Flipkart, etc

Anisha was able to crack Amazon after practicing questions from TutorialCup