×

Java Queue

The Java.util package has the interface Queue, which does extend the Collection interface. It is used to protect the parts that are managed using the FIFO approach.

Being an interface, the queue needs a concrete class for the declaration, and the most popular classes in Java are the LinkedList and Priority Queue. It is an ordered list of objects where new elements are added at the end and old elements are deleted at the beginning. The implementations of these classes are not thread safe. If a thread-safe implementation is required, PriorityBlockingQueue is an option.

Queue Interface Statement:

It is stated that the Queue interface is:

public interface Queue<Q> extends Collection<Q> 

Creating queue objects:

The queue is an interface; hence it is not possible to create objects of the type of queue. To build an object, we always need a class that extends this list. Additionally, because Java 1.5 included Generics, it is now able to limit the kinds of objects that can be stored in the Queue.

This type-safe queue is described as follows:

Queue<O> queue = new PriorityQueue<O> (); 

Methods of Java Queue Interface:

      Method                                      Description
Boolean add(object)It is utilized to successfully add the provided element to this queue and returns true.
Boolean offer(object)It's employed to add the desired element to this queue.
Object remove()It is employed to recover and get rid of the queue's head.
Object poll()If the queue is empty, it returns null; otherwise, it obtains and removes the queue's head.
Object element()It is employed to obtain the head of this queue but does not remove it.
Object peek()If the queue is empty, it returns null, otherwise, it obtains the head of the queue without removing it.

Queue Characteristics

  • The queue is utilized to add elements to the end of the queue and delete items from the queue's beginning. It uses the FIFO principle.
  • All Collection interface methods, such as insertion, deletion, etc., are supported by the Java Queue.
  • The most popular implementations are PriorityQueue, ArrayBlockingQueue, and LinkedList.
  • If a null action is performed on a blocking queue, a NullPointerException is raised.
  • Unbounded Queues are the Queues included in java.util package.
  • The Bounded Queues are the Queues that are included in the java.util.concurrent package.
  • All other queues do not allow insertion or removal, but the Deque does at the tail and head of the queue, respectively. The Deques permit the addition and elimination of components from either end.

Example:

QueueExpl1.java

import java.util.*;
 class QueueExpl1 {
  
    public static void main(String args[])
    {
        Queue<String> q = new PriorityQueue<>();
  
        q.add("Welcome");
        q.add("To");
        q.add("JavaTpoint");
        System.out.print(q);
        q.remove("Welcome");
        System.out.print(q);
    }
}

Output:

Java Queue

The following classes support the Queue Interface:

Priority Queue class:

Another class defined in the collection framework, PriorityQueue, provides a method for prioritizing objects as they are processed. In the Java queue, object insertion and deletion are described as following a FIFO pattern. However, a PriorityQueue can be used when it is necessary to process queue elements in accordance with their priority.

PriorityQueue Class Declaration:

Let's examine the java.util.PriorityQueue class declaration.

public class PriorityQueue<E> extends AbstractQueue<E> implements Serializable

Let us understand more about this using an example.

Priority Queue Example

PriorityQueueExpl.java

import java.util.*;  
class PriorityQueueExpl{  
public static void main(String args[]){  
PriorityQueue<String> q = new PriorityQueue<String>();  
q.add("Welcome");  
q.add("to");  
q.add("Java");  
q.add("T");  
q.add("point");  
System.out.println(" "+q.element());  
System.out.println(" "+q.peek());  
System.out.println(" repeating the queue's components ");  
Iterator i = q.iterator();  
while(i.hasNext()){  
System.out.println(i.next());  
}  
q.remove();  
q.poll();  
System.out.println("after eliminating two components:");  
Iterator<String> i2=q.iterator();  
while(i2.hasNext()){  
System.out.println(i2.next());  
}  
}  
}  

Output:

Java Queue

LinkedList:

The collection framework's built-in class LinkedList implements the linked list data structure by default. Each element is a discrete object with a data piece and an address section, and the components are not retained in sequential locations. It is a linear data structure. The elements are linked together via pointers and addresses. Every component is known as a node. Because of their dynamic nature and ease of insertions and removals, they are preferred to queues or arrays. Let's examine how to create a queue object using this class.

Let us understand more about this using an example.

LinkedListExpl.java

import java.util.*;
class LinkedListExpl
 {
 public static void main(String args[])
    {
        // Empty LinkedList is created
        Queue<Integer> ll1 = new LinkedList<Integer>()
// Adding elements to the ll1
        ll1.add(1);
        ll1.add(2);
        ll1.add(5);
 // Topmost element is printed
        System.out.println(ll1.peek());
        System.out.println(ll1.poll());
       // Topmost element is printed
        System.out.println(ll1.peek());
    }
}

Output:

Java Queue

Priority Blocking Queue:

It should be emphasized that neither the PriorityQueue nor the LinkedList implementations are thread safe. If a thread-safe solution is required, one possibility is PriorityBlockingQueue. An unbounded blocking queue that offers to block retrieval operations and adheres to the same ordering rules as the PriorityQueue class is the PriorityBlockingQueue.

Due to resource exhaustion brought on by adding elements occasionally failing with an OutOfMemoryError due to its unbounded nature.

Let us understand with an example.

PBQExpl.java

import java.util.concurrent.PriorityBlockingQueue;
import java.util.*;
class PBQExpl {
    public static void main(String args[])
    {
        // Empty Priority Blocking Queue is created
        Queue<Integer> pbq1 = new PriorityBlockingQueue<Integer>();
   // Adding items to the pbq1
        pbq1.add(1);
        pbq1.add(2);
        pbq1.add(5);
  
        // Top most element is printed
        System.out.println(pbq1.peek());
  
        // Top most element is printed and
        // it is removed from Priority Block Queue
        System.out.println(pbq1.poll());
  
        // Top most element is printed
        System.out.println(pbq1.peek());
    }
}

Output:

Java Queue

Related Topics

How to use scanner in Java

Scanner class in Java is the part of java.util package. Java programming language has various ways to read input from the user, Scanner class is one of the classes to...

5 minutes read.

Java FileOutputStream

What is FileOutputStream?When we need raw stream data written into a file, we need to look for another option: FileOutputStream. It is used when the file's data is byte-oriented. It comes under...

4 minutes read.

How to uninstall the Java in Ubuntu

We need java on our computers in our daily lives because there are lots of different applications that are developed using the java environment, so we have to install java...

4 minutes read.

Shopping Bill in Java

Java Shopping Bill Here in this program, we are about to create a JAVA class called Products which will have some properties or attributes like prod_name (Product Name ), qty (quantity),...

4 minutes read.

How to Compare Two Strings in Java

How to Compare Two Strings in Java On the basis of reference or content, one can compare two strings in Java. String comparison is used in reference matching (== operator), sorting...

4 minutes read.

Stable Marriage Problem in Java

Given N men and N women, the Stable Marriage Problem asks you to match up the men and women in such a way that there are never any two people...

6 minutes read.

Snake and Ladder Problem in Java

Find the smallest number of dice throws necessary to reach the destination or last cell from the source or first cell on a snake and ladder board. Essentially, the player...

6 minutes read.

Time Class Operation in Java

The Java SQL package includes the time class. This class is merely a lightweight wrapper for java. util. THANKS TO THE recognize BC API can recognize this as a SQL...

3 minutes read.

Java String vs StringBuffer

Java String vs StringBuffer In this section, we will discuss the key differences between String and StringBuffer class. Before moving to the ahead in this section, let’s introduce with both classes. String...

4 minutes read.

Java Type Casting

Type casting is a technique or process used in Java to convert one data type into another, either manually or automatically. The compiler performs the automatic conversion, and the programmer...

3 minutes read.

Method Overriding in Java

Overriding  Overriding is also known as run time polymorphism, and it is about the same method with the same signatures in different classes. Overriding can be applied only methods. Method Overriding Method Overriding...

8 minutes read.

nth Prime Number in Java

A number is considered prime if only divisible by one and itself. Prime numbers include, for example, 2, 3, 5, 7, 11, etc. In looking at it another way, a...

5 minutes read.

Adapter class in Java

By using the adapter classes, we can implement Listener interfaces. With the help of adapter classes, we can save code as it provides all implementation methods of listener interfaces Advantages of...

3 minutes read.

AES 256 Encryption in Java

Now a days, security has grown in importance. Java programming supports a variety of encryption and hashing methods, which offers security for data transport and communication among various nodes. In...

4 minutes read.

Narcissistic Number in Java

A Narcissistic number is made up of digits that have been added together and raised to powers equal to the number of digits in the original number. In those other...

3 minutes read.

Iccanobif Numbers in Java

In this article, you will be very well equipped with the knowledge of iccanobif numbers in Java. You will also know how they are formed and basic example programs on...

3 minutes read.

Synchronized Keyword in Java

Synchronization is the process of limiting access to a shared resource or data to a single thread at a given moment in time. This aids in shielding the data from...

6 minutes read.

Leap Year Program in Java

Leap Year Program in Java: A leap year is a calendar year that have an extra day i.e. 366 days instead of 365 days is called leap year. In other...

2 minutes read.

Check the presence of Substring in a String in java

In java, the string can be treated as class and datatype. The string contains words and numbers but should be in double-quotes. Example: ” Omsairam” Substring The part of the string is called...

2 minutes read.

Java TreeMap

TreeMap in Java with Example Java TreeMap implements the NavigableMap interface. It extends Map Interface. Java TreeMap is based on the red-black Tree implementation. It stores the key-value pair in sorted...

7 minutes read.