top

Search

Java Tutorial

.

UpGrad

Java Tutorial

Queue in Java

Introduction

Queue in Java is a data structure for handling collections of duplicate items. The elements are stored in first-in, first-out (FIFO) queues. The line begins at the front and extends to the rear. Each Queue method has an exception-throwing and a value-returning variant in case the former fails.  

Operations on Queue Interface

The queue interface provides a number of java queue methods for managing queues and completing their associated tasks.

The two extremes of the linear data structure known as a queue are the first and last positions in the Queue. The Queue is constantly being added to and emptied of its constituent parts. 

Java's Queue interface may be found in the Java.util package. The Collection interface is also expanded upon.

Here are the operations performed on Queue Interface:

Adding Elements

An item can be added to the Queue with the method add(). The Java Priority Queue does not remember the sequence in which items were added. The components are saved in a priority order by default. An Exception is issued if the add() method cannot be executed.

Example:

import java.util.*;
public class LIB {
    public static void main(String args[])
    {
        Queue<String> pq = new PriorityQueue<>();
        pq.add("Love");
        pq.add("Is");
        pq.add("Blind");
        System.out.println(pq);
    }
}

Output: 

[Love, Is, Blind]

Removing Elements

The remove() method is used to remove an element from a Queue. The first item in the queue will be removed. In cases when there is more than one, the oldest one will be removed. The head can alternatively be removed and returned with the poll() function. If the Queue is empty, then a NoSuchElementException will be thrown.

Example:

Queue<String> daysOfTheWeek = new LinkedList<String>();
daysOfTheWeek.add("Monday");
daysOfTheWeek.add("Tuesday");
daysOfTheWeek.add("Wednesday");

String day = daysOfTheWeek.remove();
System.out.println(day);

In 1st line= A daysOfTheWeek queue is made. The implementation is a java queue linked list.
In 2nd to 4th line= We use the add procedure to bolster the queue with new elements.
In 5th line= Monday, the queue's head, is deleted with the remove()  method.
In 6th line= The subtracted value is shown.

Iterating the queue

To remove a value from a Queue, use the remove() method. The item at the head of the queue is deleted. When more than one of these is found, the oldest one will be deleted. The head can alternatively be removed and returned with the poll() function. If the Queue is empty, then a NoSuchElementException will be thrown.

Example:

import java.util.*;

public class HRY {

    public static void main(String args[])
    {
        Queue<String> pq = new PriorityQueue<>();

        pq.add("How");
        pq.add("Are");
        pq.add("You");

        Iterator iterator = pq.iterator();

        while (iterator.hasNext()) {
            System.out.print(iterator.next() " ");
        }
    }
}

Output

Are How You

Characteristics of a Queue?

  • The Queue can be used to add items to the tail end or remove them from the front. A "first-in, first-out" system is used.

  • Insertions, removals, and everything else, is completely supported by the Java Queue class.

  • The most common queue java implementations are the linked list, the array blocking queue, and the priority queue.

  • A NullPointerException is triggered if a null operation is attempted on a BlockingQueue.

  • Unbounded Queues can be found in the java.util package.

  • Bounded Queues can be found in the java.util.concurrent package.

  • Except for the Deques, all other queues allow for items to be added to or removed from the queue at either the tail or the head. Element insertion and removal are supported on both ends of the Deques. 

Classes that Implement the Queue Interface

Given that Queue is an interface, we are unable to provide its concrete implementation. Use of Queues features requires classes that implement its interface.

Priority Queue

Priority queues sort items in order of how quickly they need to be handled. Priority items are typically retrieved before lesser priority items. An item with a greater priority value in a priority queue will be closer to the front of the queue than one with a lower priority value.

Program:

import java.util.*;

class GfG {

    public static void main(String args[])
    {
  
        Queue<Integer> pQueue
            = new PriorityQueue<Integer>();

        pQueue.add(10);
        pQueue.add(20);
        pQueue.add(15);

        System.out.println(pQueue.peek());
        System.out.println(pQueue.poll());
        System.out.println(pQueue.peek());
    }
}

Output:

10

10

15

Linked List

In the collection framework, the linked list data structure is implemented by the LinkedList class. Each node in this linear data structure has its own data component and address part, and nodes are not always physically adjacent to one another. Using addresses and pointers, the components are interconnected. A node is any individual component.

Program:

import java.util.*;

class GfG {

    public static void main(String args[])
    {
        Queue<Integer> ll
            = new LinkedList<Integer>();

        ll.add(10);
        ll.add(20);
        ll.add(15);


        System.out.println(ll.peek());
        System.out.println(ll.poll());
        System.out.println(ll.peek());
    }
}

Output:

10

10

2

PriorityBlockingQueue

The PriorityBlockingQueue refers to an unbounded blocking queue that provides blocking retrieval operations and follows the same ordering principles as class PriorityQueue. Due to its infinite size, it may throw an OutOfMemoryError if its resources are depleted while trying to add more items. No null values are allowed in this class. 

The PriorityBlockingQueue class and its iterator fully support all of the methods defined by the Collection and Iterator interfaces, including all of the convenience methods. 

The order of equally important items is not guaranteed by operations on this class. If you need to strictly enforce a certain order, you can do so by creating special comparators or classes that employ a secondary criterion to separate otherwise equal items. 

In Java, the Collections Framework is home to classes like this one.

Methods of Queue Interface?

The Queue interface has several buttons for adding, removing, and reviewing queued items. The following are examples of some of the most common queue java methods:

  • add(element): To add an item to the end of the queue, use add(element). An exception is thrown if the queue is already at capacity.

  • offer(element): Use add(element) to append an item to the end of the Queue. If the Queue is full, an error is generated.

  • remove(): The remove() function takes the item at the head of the queue and returns it. An error is generated if the queue is empty.

  • poll(): To retrieve and replace the item at the queue's head, call java queue poll function. If the Queue contains no items, then the result will be null.

  • element(): Retrieves the initial item in the Queue without removing it from the queue. An error is generated if the queue is empty.

  • peek(): Without removing it from the queue, peek() returns the item that is now at the front. If there is nothing on the queue, it will return null.

Advantages of Queue Interface in Java

  • Massive data sets can be easily and efficiently managed.

  • Operations like insertion and deletion are simplified by the first-in, first-out structure.

  • Thread-safe Queue implementations include the Java.util.concurrent.ConcurrentLinkedQueue class. This means that the Queue can be used concurrently by a large number of threads without causing any issues.

  • The interface of Queue is helpful for handling collections of elements in performance-critical applications because it
    implements efficiently adding, removing, and checking members.

  • When numerous people are waiting for the same service, queues are efficient.

  • When it comes to passing data between processes, queues are lightning quick.

  • Other data structures can be implemented utilizing queues.

  • As a special case of the more general Collection interface, the Queue interface can be combined with a wide variety of data structures and algorithms.

Disadvantages Of Queue Interface In Java

  • Functional constraints: The Queue interface has limited capabilities because it was built for maintaining ordered groups of items and might not be appropriate for more complicated algorithms.

  • Complexity: A lack of knowledge of data structures and algorithms can make the Queue interface confusing and challenging to use for new programmers.

  • Limits on growth: The Array Deque class and other fixed-size Queue implementations have limits on the quantity of elements they can hold.

  • Memory Usage: If the Queue interface is implemented to remember the components' relative positions, it could consume greater memory than any other data structure.

Queue Interface Declaration

The queue is an interface that must be implemented by a concrete class at declaration; in Java, the most popular implementations are the linked list and the priority queue. These classes' implementations are not thread-safe. PriorityBlockingQueue can be used if a thread-safe implementation is necessary.

The declaration of the Queue interface is as follows: 

public interface Queue extends Collection 
Queue Java Beispiel:
import java.util.LinkedList;
import java.util.Queue;

public class QueueExample {

    public static void main(String[] args)
    {
        Queue<Integer> q
            = new LinkedList<>();
        for (int i = 0; i < 5; i )
            q.add(i);
        System.out.println("Elements of queue "
                        q);

        int removedele = q.remove();
        System.out.println("removed element-"
                        removedele);

        System.out.println(q);
        int head = q.peek();
        System.out.println("head of queue-"
                        head);
        int size = q.size();
        System.out.println("Size of queue-"
                        size);
    }
}

Output: 

Elements of queue [0, 1, 2, 3, 4]

removed element-0

[1, 2, 3, 4]

head of queue-1

Size of queue-4

Basic Features of a Queue

A queue, like a stack, is a type-specific ordered list.

  • First-come, first-served is how the Queue works.

  • In order to make room for a new item in the Queue, everything in the Queue must be removed first.

  • The peek() function is frequently used because it returns the value of the first entry in the queue without the need for dequeuing.

Conclusion

The comprehensive guide has educated us on the Queue data structure, the Java Queue Interface, the class tree, and the fundamental methods of the Java Queue class. We have also looked at the many implementation classes and sub-interfaces of the Queue interface, as well as its key characteristics, examples of use, and practical applications. For any further information, you can refer to the upGrad website.

FAQs

1. Can you explain the various queues found in data structures?

Following are the different java queue types:

  • Simple Queue

  • Priority Queue

  • Double Ended Queue

2. What are the most prominent external interfaces that queues offer?

insert(): Inserts a new data item at the queue's tail with the insert() function.

remove(): The remove() method takes an item off the end of the queue.

peek(): The item is not deleted from the queue but rather returned to the top.

 isFull()Returns true if the queue is full.

 isEmpty()Returns true if the queue is empty; false otherwise.

3. Can you explain what Deques are?

It is possible to insert objects into a deque from either the front or the back, and to remove them in the same way. Several of Deques' techniques, such as insertLeft(), insertRight(), removeLeft(), and removeRight(), translate to the usual insertion and removal procedures.

4. What are priority queues and how do they function?

Priority queue items are sorted by key frequency of use. Therefore, in a priority queue, the item with the lowest value (or the highest value, depending on the sequence) is always selected.

Leave a Reply

Your email address will not be published. Required fields are marked *