Queue in Java with Example | Java Queue Declaration, Creation, Implementation, Methods

Queue in Java is an interface that is present in java.util package. It extends the collection interface. A Queue is an ordered list in which element insertions are done at one end(rear) and deletions are done at the other end(front). The Queue interface basically orders the elements in FIFO(first-in, first-out) manner.

A railway reservation counter is our daily life example of a Queue, where the people stand outside the reservation counter. The person who comes in the last is standing in the last of the line and the person who gets the ticket is removed from the beginning of the Queue.

Queue in Java with Example 1

Key Points to Remember Regarding the Queue Interface

  1. Child interface of collection interface.
  2. Null values are not allowed.
  3. Duplicates values are not allowed.
  4. Heterogeneous elements are allowed.
  5. Based on the FIFO manner.
  6. LinkedList and PriorityQueue are two implementation classes of the Queue interface.
  7. We cannot instantiate it because it is an interface, rather than create the instance of LinkedList or PriorityQueue.

Queue Interface Declaration

public interface Queue extends Collection

Creating Queue Objects | How to Create a Queue in Java?

As Queue is an interface we can’t create objects of the type queue. we always need a class in order to create an object. After Generics introduction in Java 1.5, we can restrict the type of object stored in the Queue. Safe-Queue can be defined as follows

// Obj is the type of the object to be stored in Queue Queue queue = new PriorityQueue ();

Read More:

Methods of Java Queue Interface

1. boolean add(Object): This method is used to insert the specified element at the end of the queue. It returns true if the element is successfully inserted. It throws an exception if no space is currently available in the queue.

2. Object remove(): This method is used to remove the element at the head of the Queue and returns its value. It throws NoSuchElementException if the queue is empty.

3. Object peek(): This method returns the element at the head of the queue without removing the element. It returns null if the queue is empty.

4. Object poll(): This method is similar to the remove() method but the only difference is it returns null if the Queue is empty.

5. Object element(): This method returns the element at the head of the queue, the element is not removed. It throws NoSuchElementException if the queue is empty.

6. boolean offer(Object obj): This method is used to insert the specified element into this queue. It returns true if the element is successfully inserted otherwise it returns false.

Java Queue Program for Add

import java.util.*;
class Examplequeue{

public static void main(String args[]){
Queue queue = new LinkedList();

//adding element into this queue
queue.add("Amit");
queue.add("Raaj");
queue.add("Ajay");
queue.add("Vijay");
queue.add("Rahul");

//Queue methods operations
System.out.println("The Queue elements are: " +queue);
System.out.println("The removal element is: " +queue.remove());
System.out.println("After remove Queue elements are: " +queue);
System.out.println("Queue head element is: " +queue.peek());
System.out.println("Return Queue elements: " +queue.poll());
System.out.println("After remove Queue elements are: " +queue);
System.out.println("Return Queue elements without removing: " +queue.element());
System.out.println("After all operations Queue elements are: " +queue);
}
}

Output:

Queue in Java with Example 2

Java Queue Example peek() vs element()

import java.util.*;
class Examplequeue{
public static void main(String args[]){
Queue q = new LinkedList();

//Queue methods operation
System.out.println("Head Queue element: " +q.peek()); //return null
System.out.println("Return Queue element: " +q.element()); //throws exception
}

}

Output:

Queue in Java with Example 3

Java Queue Example remove() vs poll()

import java.util.*;
class Examplequeue{
public static void main(String args[]){
Queue q = new LinkedList();

//Queue methods operation
System.out.println("The removal Queue element: " +q.remove()); //throws exception
System.out.println("Return Queue element: " +q.poll()); //return null
}

}

Output: In case of remove() method

Queue in Java with Example 4

Output: In case of poll() method

Queue in Java with Example 5

Queue Interface Operations

Let us discuss in detail how to perform basic operations on the queue using the Priority Queue Class.

Adding Elements: In order to an Element in the Queue, we use the add method(). Priority Queue will not retain the Insertion Order and elements are sorted depending on the priority order that is ascending by default.

Removing Elements: To Remove an element from the Queue we use the remove method(). In the case of multiple objects, we remove the first occurrence of the object. In addition to this method, we can also go with a poll() method to remove the head and return it.

Iterating the Queue: There are several ways to iterate through the Queue. Among all of them, the famous one is to convert the queue to array and then traverse using the for loop. You can also use the built iterator of the queue to iterate the queue.

Characteristics of a Queue

Below are some of the characteristics of the queue and all of them are explained in detail.

  • Used for Insertion of Elements at the end of the queue and removing the elements from the beginning of the queue. It follows the First In First Out Concept.
  • Java Queue supports all methods of Collection Interface such as Insertion, Deletion, etc.
  • Priority Queue, LinkedList, ArrayBlocking Queue are the most commonly used Implementations.
  •  On Performing a Null Operation on Blocking Queues, NullPointer Exception is obtained.
  • Queues present in java.util package is Unbounded Ones and the ones present in java.util.concurrent package is the Bounded Ones.
  • All other Queues other than Deques support insertion and removal at the beginning and end respectively. However, Deques support element insertion and removal at both ends.

How to Use a Queue in Java?

In order to use a Queue in Java, we need to import the queue interface at first.

import java.util.queue;

or

import java.util.*;

Once importing is done you can create a Queue as shown below

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

Since Queue is an Interface we use Linked List Class which implements the Queue Interface to create a Queue Object.

We can also write Queue using other classes like an array, priority queue such as below

Queue<String> str_pqueue = new PriorityQueue<> ();
Queue<Integer> int_queue = new ArrayDeque<> ();

As Queue Object is Created we can initialize the Queue Object by giving values to it using the add method() as follows.

str_queue.add(“one”);
str_queue.add(“two”);
str_queue.add(“three”);

Queue Implementation in Java

Classes that implement the Queue Interface are given in detail and they are as follows

Priority Queue: Priority Queue Class implemented in the collection framework gives us a way to process the objects depending on the Priority. Queue usually follows the First-In-First-Out Algorithm and at times elements of the Queue need to be processed as per the priority and that’s where Priority Queue comes into the picture. Know What is Priority Queue in Java with Example provided below.

// Java program to demonstrate the
// creation of queue object using the
// PriorityQueue class

import java.util.*;

class GfG {

public static void main(String args[])
{
// Creating empty priority queue
Queue<Integer> pQueue
= new PriorityQueue<Integer>();

// Adding items to the pQueue
// using add()
pQueue.add(10);
pQueue.add(20);
pQueue.add(15);

// Printing the top element of
// the PriorityQueue
System.out.println(pQueue.peek());

// Printing the top element and removing it
// from the PriorityQueue container
System.out.println(pQueue.poll());

// Printing the top element again
System.out.println(pQueue.peek());
}
}

Output:

10
10
15

Linked List: Linked List is a Class implemented in the collection framework and inherently implements the linked list data structure. It is a linear data structure in which all the elements are stored in contiguous locations and each and every element is a separate object having both data and address parts. Elements are linked using pointers and addresses. Every Element is called a node. Due to the dynamicity and ease of insertions, deletions that come with Linked List are preferred over arrays and queues. Check out the following program to understand how to create a Queue in Java using the LinkedList.

// Java program to demonstrate the
// creation of queue object using the
// LinkedList class

import java.util.*;

class GfG {

public static void main(String args[])
{
// Creating empty LinkedList
Queue<Integer> ll
= new LinkedList<Integer>();

// Adding items to the ll
// using add()
ll.add(10);
ll.add(20);
ll.add(15);

// Printing the top element of
// the LinkedList
System.out.println(ll.peek());

// Printing the top element and removing it
// from the LinkedList container
System.out.println(ll.poll());

// Printing the top element again
System.out.println(ll.peek());
}
}

Output:

10
10
20

Priority Blocking Queue: Priority Queue and Linked List Implementations aren’t thread-safe. Priority Blocking Queue is an alternative implementation if in case you need a thread-safe implementation. It is an Unbounded Blocking Queue and uses the Same Ordering Rules similar to Priority Queue and provides Blocking Retrieval Operations.

As it Unbounded it might fail sometimes while adding elements due to memory exhaustion and results in OutofMemory Error. Check out the Blocking Queue in Java with Example.

// Java program to demonstrate the
// creation of queue object using the
// PriorityBlockingQueue class

import java.util.concurrent.PriorityBlockingQueue;
import java.util.*;

class GfG {
public static void main(String args[])
{
// Creating empty priority
// blocking queue
Queue<Integer> pbq
= new PriorityBlockingQueue<Integer>();

// Adding items to the pbq
// using add()
pbq.add(10);
pbq.add(20);
pbq.add(15);

// Printing the top element of
// the PriorityBlockingQueue
System.out.println(pbq.peek());

// Printing the top element and
// removing it from the
// PriorityBlockingQueue
System.out.println(pbq.poll());

// Printing the top element again
System.out.println(pbq.peek());
}
}

Output:

10
10
15