New Tutorials:   TKINTER    KOTLIN    JAVASCRIPT    SASS/SCSS    PL/SQL    Matplotlib    C++ Programs
CLOSE
   Java  Data Structure  Queue  
   Technology    Programming

Queue Implementation in Java

         
 AUGUST 1, 2020   by mohitg2302

The concept of a Queue data structure is similar to the queue we come across in our day to day life like at a bus stop, or at ticketing counter of a railway station, queue at an ATM Machine to withdraw cash, etc. In all these examples the person who first enters the queue receives the ticket or cash first. Hence we can say that the Queue's working principle is based on First-In-First-Out(FIFO).

queue implementation in Java

A Queue is a linear data structure in which elements are inserted from one end called Rear and is removed from the other end called Front.

The value of both Rear and Front is set to -1 initially and then these values are incremented or decremented as the elements are inserted and deleted.

Basic Functions of Queue

enqueue: It is used to add an element at the rear of the queue.

dequeue: It is used to remove an element from the front of the queue.

IsEmpty: It is used to check whether the queue is empty or not.

IsFull: It is used to check whether the queue is full or not.

peek: It is used to return the front value without removing it.

The complexity of enqueue and dequeue operations in a queue using an array is O(1).

Although the use of all kinds of abstract data types such as Stack, Queue, and LinkedList is provided in Java it is always desirable to understand the basics of the data structure and implement it accordingly.

1. Queue Implementation in Java using Array

So here we will implement a queue data structure using an array in Java.

import java.util.*;

// define queue class
class Queue 
{
    int arr[], front, rear, cap, n1;  		
	
    // Queue constructor
	Queue(int n)
	{
		arr = new int[n];
		cap = n;
		front = 0;
		rear = -1;
		n = 0;
	}

	// dequeue function for removing the front element
	public void dequeue()
	{
		// check for queue underflow
		if (isEmpty())
		{
			System.out.println("No items in the queue,cannot delete");
			System.exit(1);
		}

		System.out.println("Deleting " + arr[front]);

		front = (front + 1) % cap;
		n1--;
	}

	// enqueue function for adding an item to the rear
    public void enqueue(int val)
	{
		// check for queue overflow
		if (isFull())
		{
			System.out.println("OverFlow!!Cannot add more values");
			System.exit(1);
		}

		System.out.println("Adding " + val);

		rear = (rear + 1) % cap;
		arr[rear] = val;
		n1++;
	}

	// peek function to return front element of the queue
	public int peek()
	{
		if (isEmpty()) 
		{
			System.out.println("Queue empty!!Cannot delete");
			System.exit(1);
		}
		return arr[front];
	}

	// returns the size of the queue
	public int size()
	{
		return n1;
	}

	// to check if the queue is empty or not
	public Boolean isEmpty()
	{
		return (size() == 0);
	}

	// to check if the queue is full or not
	public Boolean isFull()
	{
		return (size() == cap);
	}
	
	// Queue implementation in java
	public static void main (String[] args)
	{
		// create a queue of capacity 5
		Queue q = new Queue(5);

		q.enqueue(10);
		q.enqueue(20);
		q.enqueue(30);
		
		System.out.println("Front element is: " + q.peek());
		q.dequeue();
		System.out.println("Front element is: " + q.peek());

		System.out.println("Queue size is " + q.size());

		q.dequeue();
		q.dequeue();
		
		if (q.isEmpty())
			System.out.println("Queue Is Empty");
		else
			System.out.println("Queue Is Not Empty");
	}
}


Adding 10
Adding 20
Adding 30
Front Element is:10
Deleting 10
Front Element is:20
Queue size is 2
Deleting 20
Deleting 30
Queue is empty

2. Queue Implementation in Java using Queue Interface

Queue interface is a part of Java Collections that consists of two implementations:

LinkedList and PriorityQueue are the two classes that implement the Queue interface.

implement queue in java

Since the Queue is an interface, we cannot create an instance of it. Hence we create the instance of the LinkedList and the PriorityQueue class and assign it to the queue interface.

Queue q1 = new LinkedList();
Queue q2 = new PriorityQueue();

There are mainly five operations of the Queue interface. They are:

boolean add(E e): This method is used to add a specific element at the end of the queue. Since its return type is boolean, it returns true if the element is added successfully else return false.

E element(): This method returns the first element of the queue.

E remove(): This method removes the first element of the queue.

E poll(): This method is similar to that of a remove(), but the only difference is that the poll returns null if the queue is empty.

E peek(): This method is similar to that of an element(), but the only difference is that element returns null if the queue is empty.

Let us learn these operations using examples:

i) Using LinkedList Class

import java.util.*;
public class QueueExample1 
{	 
   public static void main(String[] args) 
   {
	  Queue<String> q = new LinkedList<String>();
	    
      //Adding elements to the Queue
      q.add("Mohit");
      q.add("Priyanka"); 
      q.add("Prabhat");
      q.add("Pranjal");
      q.add("Anilanshu");
       
      System.out.println("Elements in Queue:"+q);

      System.out.println("Removed element: "+q.remove());

      System.out.println("Head: "+q.element());

      System.out.println("poll(): "+q.poll());

      System.out.println("peek(): "+q.peek());

      System.out.println("Elements in Queue:"+q);
   }
}


Elements in Queue:[Mohit, Priyanka, Prabhat, Pranjal, Anilanshu]
Removed element: Mohit
Head: Priyanka
poll(): Priyanka
peek(): Prabhat
Elements in Queue:[Prabhat, Pranjal, Anilanshu]

ii) Using PriorityQueue Class

import java.util.*;
public class QueueExample2 
{ 
   public static void main(String[] args) 
   {
	  Queue<Integer> q2 = new PriorityQueue<Integer>();
	    
      //Adding elements to the Queue
      q2.add(10);
      q2.add(20); 
      q2.add(30);
      q2.add(40);
      q2.add(50);
  
      System.out.println("Elements in Queue:"+q2);

      System.out.println("Removed element: "+q2.remove());

      System.out.println("Head: "+q2.element());
	    
      System.out.println("poll(): "+q2.poll());

      System.out.println("peek(): "+q2.peek());

      System.out.println("Elements in Queue:"+q2);
   }
}


Elements in Queue:[10,20,30,40,50]
Removed element: 10
Head: 20
poll(): 20
peek(): 30
Elements in Queue:[30,40,50]

Conclusion

With this, we have covered the Queue Data Structure in Java. We will be covering the other Data Structures too. Happy Learning.

If we missed any function, please do share it with us in the comment section.


RELATED POSTS



Subscribe and receive amazing posts directly in your inbox.