Tutorial Playlist
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.
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:
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]
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.
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
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 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
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
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.
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:
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
A queue, like a stack, is a type-specific ordered list.
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.
1. Can you explain the various queues found in data structures?
Following are the different java queue types:
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.
PAVAN VADAPALLI
Popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. upGrad does not make any representations regarding the recognition or equivalence of the credits or credentials awarded, unless otherwise expressly stated. Success depends on individual qualifications, experience, and efforts in seeking employment.
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...