Skip to main content

Queue interface in Java with examples | Which are implementation classes of Queue?

Queue interface with ArrayDeque, LinkedList, PriorityQueue Implementation classes

Queue interface with ArrayDeque, LinkedList, PriorityQueue Implementation classes

Queue Interface (java.util.queue)

Queue is child interface of Collection Framework in Java. 

Queue provides First In First Out (FIFO) order on elements.

How to use Queue interface?

As Queue is interface, we must have class to implements queue. See below code for Queue implementation classes.

Queue priorityQueue = new PriorityQueue();

Queue arrayDqueue = new ArrayDeque();

Queue linkedList = new LinkedList(); 

LinkedList class is also implementation of List Interface.

Methods of Queue interface :

  • add() - Insert the element in the queue. Throws IllegalStateException if no space available.
  • offer() - Insert the element in the queue.
  • element() - Return head of queue. Throws an exception if queue is empty.
  • peek() - Return head of queue. Return null if queue is empty.
  • poll() - Remove and return head of queue. Throws and exception of queue is empty.
  • remove() - Remove and returns head of queue. Return null if queue is empty.

Priority Queue Class :

PriorityQueue class comes under java.util package.

Priority queue elements are retrieved in sorted order.

Suppose, we want to retrieve elements in the ascending order. In this case, the head of the priority queue will be the smallest element. Once this element is retrieved, the next smallest element will be the head of the queue.

It is important to note that the elements of a priority queue may not be sorted. However, elements are always retrieved in sorted order.

The elements of the priority queue are ordered according to their Comparable natural ordering, or by a Comparator provided at queue construction time, depending on which constructor is used.

The order is only valid when poping elements from the PriorityQueue.

How to create PriorityQueue?

Example 1 : PriorityQueue with String

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

public class PriorityQueueDemo {

    public static void main(String[] args) {
       
        Queue<String> queue = new PriorityQueue<String>();
        queue.add("java");
        queue.add("python");
        queue.add("js");
        queue.add("dotnet");
       
        System.out.println(queue);
    }
}

Output :

[dotnet, java, js, python]

lets see another example with Integer.

Example 2 : PriorityQueue with Integer

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

public class PriorityQueueDemo {

    public static void main(String[] args) {
       
        Queue<Integer> queue = new PriorityQueue<Integer>();
        queue.add(2);
        queue.add(1);
        queue.add(4);
        queue.add(3);
        queue.add(5);
        queue.add(8);
       
        System.out.println(queue);
       
        System.out.println("Removing element using poll() method");
        while (!queue.isEmpty()) {
            System.out.println(queue.poll());
        }
    }
}

Output :

[1, 2, 4, 3, 5, 8]
Removing element using poll() method
1
2
3
4
5
8

As we can see in output, in priority queue sorting works while removing elements not at time adding elements. 

Lets see example of priority queue methods :

Example 3 : PriorityQueue methods demo

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

public class PriorityQueueDemo {

    public static void main(String[] args) {
       
        Queue<Integer> queue = new PriorityQueue<Integer>();
        queue.add(2);
        queue.add(1);
        queue.add(4);
        queue.add(3);
        queue.add(5);
       
        // offer method for adding elements
        queue.offer(8);
       
        System.out.println("Retrieves head of queue : "+queue.peek());
       
        System.out.println("Retrieves and Remove head of queue : "+queue.poll());
       
        System.out.println("Elements is present or not : "+queue.contains(1));
       
    }
}

Output :

Retrieves head of queue : 1
Retrieves and Remove head of queue : 1
Elements is present or not : false

LinkedList Class :

LinkedList class implements Queue interface as well as List interface also.

Learn more about Linkedlist :

ArrayDeque Class :

ArrayDeque implements Deque interface and Deque interface extends Queue interface.

It is part of java.util package.

ArrayDeque follows insertion order. means while displaying ArrayDeque elements the result set would be having the same order in which the elements got inserted into the queue.

Example 4 : ArrayDeque class demo

import java.util.ArrayDeque;

public class ArrayDequeDemo {

    public static void main(String[] args) {

        ArrayDeque<Integer> queue = new ArrayDeque<>();
        queue.add(2);
        queue.add(1);
        queue.add(4);
        queue.add(3);
        queue.add(5);
       
        // offer method for adding elements
        queue.offer(8);

        // Adding elements at head
        queue.addFirst(9);
        queue.offerFirst(10);
       
        // Adding element at tail
        queue.addLast(6);
        queue.offerLast(7);
       
        System.out.println(queue);
       
        System.out.println("Access head of queue : "+queue.getFirst());
       
        System.out.println("Access tail of queue : "+queue.getLast());
       
        System.out.println("Retrieves head of queue : "+queue.peek());
       
        System.out.println("Retrieves and Remove head of queue : "+queue.poll());   

    }
}

Output :

[10, 9, 2, 1, 4, 3, 5, 8, 6, 7]
Access head of queue : 10
Access tail of queue : 7
Retrieves head of queue : 10
Retrieves and Remove head of queue : 10

As you can see some methods have same functionality like add() and offer() add an element at top of queue. so main difference is 

  • add() method throws exception if queue is full.
  • offer() method does not throw any exception if queue is full.
We can use ArrayDeque class as Stack also.

Comments

Popular posts from this blog

Plus Minus HackerRank Solution in Java | Programming Blog

Java Solution for HackerRank Plus Minus Problem Given an array of integers, calculate the ratios of its elements that are positive , negative , and zero . Print the decimal value of each fraction on a new line with 6 places after the decimal. Example 1 : array = [1, 1, 0, -1, -1] There are N = 5 elements, two positive, two negative and one zero. Their ratios are 2/5 = 0.400000, 2/5 = 0.400000 and 1/5 = 0.200000. Results are printed as:  0.400000 0.400000 0.200000 proportion of positive values proportion of negative values proportion of zeros Example 2 : array = [-4, 3, -9, 0, 4, 1]  There are 3 positive numbers, 2 negative numbers, and 1 zero in array. Following is answer : 3/6 = 0.500000 2/6 = 0.333333 1/6 = 0.166667 Lets see solution Solution 1 import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.function.*; import java.util.regex.*; import java.util.stream.*; import static jav...

Flipping the Matrix HackerRank Solution in Java with Explanation

Java Solution for Flipping the Matrix | Find Highest Sum of Upper-Left Quadrant of Matrix Problem Description : Sean invented a game involving a 2n * 2n matrix where each cell of the matrix contains an integer. He can reverse any of its rows or columns any number of times. The goal of the game is to maximize the sum of the elements in the n *n submatrix located in the upper-left quadrant of the matrix. Given the initial configurations for q matrices, help Sean reverse the rows and columns of each matrix in the best possible way so that the sum of the elements in the matrix's upper-left quadrant is maximal.  Input : matrix = [[1, 2], [3, 4]] Output : 4 Input : matrix = [[112, 42, 83, 119], [56, 125, 56, 49], [15, 78, 101, 43], [62, 98, 114, 108]] Output : 119 + 114 + 56 + 125 = 414 Full Problem Description : Flipping the Matrix Problem Description   Here we can find solution using following pattern, So simply we have to find Max of same number of box like (1,1,1,1). And ...