×

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 Assign Static Value to Date in Java?

In this tutorial, we will learn certain ways to assign a static value to a date in java. We will see the limitation of each method that will lead to...

3 minutes read.

Java String toUpperCase() methods

Java String toUpperCase() method is used to convert all the characters of the String into upper case. Syntax public String toUpperCase() public String toUpperCase(Locale locale) Returns It returns upper case String. Java String toUpperCase() Example 1: public...

1 minute read.

Applet Program in Java

Applet Program in Java An applet is a program that can be embedded in a web page. Applets programs are run by a web browser. It mainly works on the client-side....

3 minutes read.

Minimum Window Subsequence in Java

In this article, you will be very well acknowledged about the minimum window subsequence, what is the approach and how it is implemented. The example program is also executed and...

4 minutes read.

Java ResultSetMetaData

The data about another data is called Metadata. The ResultSetMetaData is used to store the data about ResultSet. The ResultSet Contains the columns, rows, names of table, datatypes etc. these...

2 minutes read.

Java.net.ConnectionException

java.net.ConnectException: Connection rejected: the interface is the most continuous sort of happening, organizing special cases in Java at whatever point the product is in client-server engineering and attempting to make...

3 minutes read.

User Defined Custom Exceptions in Java

In this tutorial, we will discuss user-defined custom exceptions with examples. Introduction In Java, we have proactively characterised, Exception classes, for example, ArithmeticException, NullPointerException, ArrayoutOfBound and so on. These built-in exceptions are...

3 minutes read.

Perfect Number in Java

The concept of a perfect number in Java will be defined in this chapter, along with creating Program code that determine whether a specific number is perfect or not. Additionally,...

4 minutes read.

Untouchable Number in Java

If a number N cannot be divided properly by any positive number, it is said to be an untouchable number. Additionally known as nonaliquot numbers. The sequence is A005114 from...

3 minutes read.

Empty Statement in Java

The three sorts of statements in Java are control, expression, and declaration statements. Additionally, another statement is referred to as an empty statement. In this section, we will discuss about...

4 minutes read.

Java Integer toUnsignedLong() method

The toUnsignedLong() method of Java Integer class returns a long value by simply converting the given argument to long after an unsigned conversion. Syntax public static long toUnsignedLong (int  x) Parameters The parameter ‘x’...

1 minute read.

Java Password Generator

Generally, we must create a strong password for security reasons. In Java, there are numerous strategies for creating secure passwords. We will learn how to create a strong password in...

4 minutes read.

How to remove special characters from String in Java

Strings in Java are Objects that are supported inside by a burn exhibit. Since exhibits are immutable (cannot develop), Strings are changeless too. A completely new String is made whenever...

5 minutes read.

Pernicious Number in Java

If the number of 1s in a number appearing in the binary representation is the prime number, such a number is known as a pernicious number. A pernicious number always corresponds to...

4 minutes read.

Type Annotations in Java

Only declarations were eligible for annotations in earlier versions of Java. With Java 8, you may now annotate any type use, including types in declarations, generics, and casts: @Encrypted String data; List<@NonNull...

6 minutes read.

Java Flags Enum

In a programming language, enumerations represent a group of named constants.For instance; the four suits in a deck of playing cards could be the enumerators Club, Diamond, Heart, and Spade,...

3 minutes read.

Java Math decrementExact() Method

The decrementExact() method of Math class returns the argument which is decremented by one, throwing an exception is the result overflows an int or long. Syntax: public static int decrementExact (int a) Parameters: The...

1 minute read.

How to Convert String to enum in Java?

In this article, we shall gain the complete knowledge about how to convert the string to enum in Java. The complete process that happens in the approach shall be discussed...

3 minutes read.

Java Set to List

In this article, you will be acknowledged about how the process of conversion from Set or HashSet to LinkedList happens and what are the possible ways involved in conversion process. First...

4 minutes read.

Java Base64 Encoding and Decoding

Introduction to Encoding and Decoding Encoding is the process of putting the sequence of characters like letters, numbers, punctuations, and other symbols into a specialised format for the efficient transmission or...

11 minutes read.