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

Sales by Match HackerRank Solution | Java Solution

HackerRank Sales by Match problem solution in Java   Problem Description : Alex works at a clothing store. There is a large pile of socks that must be paired by color for sale. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are. For example, there are n=7 socks with colors socks = [1,2,1,2,1,3,2]. There is one pair of color 1 and one of color 2 . There are three odd socks left, one of each color. The number of pairs is 2 .   Example 1 : Input : n = 6 arr = [1, 2, 3, 4, 5, 6] Output : 0 Explanation : We have 6 socks with all different colors, So print 0. Example 2 : Input : n = 10 arr = [1, 2, 3, 4, 1, 4, 2, 7, 9, 9] Output : 4 Explanation : We have 10 socks. There is pair of color 1, 2, 4 and 9, So print 4. This problem easily solved by HashMap . Store all pair of socks one by one in Map and check if any pair is present in Map or not. If pair is present then increment ans variable by 1 ...

Queen's Attack II HackerRank Solution in Java with Explanation

Queen's Attack II Problem's Solution in Java (Chessboard Problem)   Problem Description : You will be given a square chess board with one queen and a number of obstacles placed on it. Determine how many squares the queen can attack.  A queen is standing on an n * n chessboard. The chess board's rows are numbered from 1 to n, going from bottom to top. Its columns are numbered from 1 to n, going from left to right. Each square is referenced by a tuple, (r, c), describing the row r and column c, where the square is located. The queen is standing at position (r_q, c_q). In a single move, queen can attack any square in any of the eight directions The queen can move: Horizontally (left, right) Vertically (up, down) Diagonally (four directions: up-left, up-right, down-left, down-right) The queen can move any number of squares in any of these directions, but it cannot move through obstacles. Input Format : n : The size of the chessboard ( n x n ). k : The number of obstacles...