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

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...

Java Hashset HackerRank Solution | Programming Blog

Java Hashset HackerRank Solution with Explanation   Problem Statement :- In computer science, a set is an abstract data type that can store certain values, without any particular order, and no repeated values. {1,2,3} is an example of a set, but {1,2,2} is not a set. Today you will learn how to use sets in java by solving this problem. You are given n pairs of strings. Two pairs (a,b) and (c,d) are identical if a = c and b = d. That also implies (a,b) is not same as (b,a). After taking each pair as input, you need to print number of unique pairs you currently have. See full problem description in HackerRank Website :- https://www.hackerrank.com/challenges/java-hashset/problem Let's see solution of problem. import java.util.HashSet; import java.util.Scanner; public class Solution {     public static void main(String[] args) {         Scanner s = new Scanner(System.in);         System.out.println("Enter tot...