Movatterモバイル変換


[0]ホーム

URL:


Open In App

The Queue interface is part of thejava.util package. It extends theCollection interface.

  • Elements are processed in the order determined by the queue implementation (First In First Out or FIFO for LinkedList, priority order for PriorityQueue).
  • Elements cannot be accessed directly by index.
  • A queue can store duplicate elements.
Java
importjava.util.PriorityQueue;importjava.util.Queue;publicclassGeeks{publicstaticvoidmain(String[]args){// Create a PriorityQueue of IntegersQueue<Integer>pq=newPriorityQueue<>();// Adding elements to the PriorityQueuepq.add(50);pq.add(20);pq.add(40);pq.add(10);pq.add(30);// Display the PriorityQueue elementsSystem.out.println("PriorityQueue elements: "+pq);}}

Output
PriorityQueue elements: [10, 20, 40, 50, 30]

Note:PriorityQueue arranges elements according to priority order (ascending by default), not insertion order.

Declaration of Java Queue Interface

public interface Queue extends Collection

We cannot instantiate a Queue directly as it is an interface. Here, we can use a PriorityQueue class that implements this interface.

Queue<Obj> queue = new LinkedList<Obj>();

Hierarchy of Queue Interface

It extends theCollection interface and has implementations likeLinkedList,ArrayDeque,PriorityQueue.

Queue

Common Implementations of Queue Interface

  • LinkedList:A FIFO queue that allows null elements and implements both Queue and Deque interfaces.
  • ArrayDeque: A resizable array-based queue that is faster than LinkedList and does not allow nulls.
  • PriorityQueue: A queue where elements are processed according to their priority instead of insertion order.
  • ConcurrentLinkedQueue: A thread-safe, non-blocking queue suitable for concurrent environments.
  • BlockingQueue: A thread-safe queue that supports blocking operations for producer-consumer scenarios.

Different Operations on Queue Interface using PriorityQueue class

1. Adding Elements

To add an element in a queue, we can use theadd() method. The insertion order is not retained in the PriorityQueue. The elements are stored based on the priority order which is ascending by default. 

Java
importjava.util.*;publicclassGeeks{publicstaticvoidmain(Stringargs[]){Queue<String>pq=newPriorityQueue<>();pq.add("Geeks");pq.add("For");pq.add("Geeks");System.out.println(pq);}}

Output
[For, Geeks, Geeks]

2. Removing Elements

To remove an element from a queue, we can use theremove() method. If there are multiple objects, then the first occurrence of the object is removed. Thepoll() methodis also used to remove the head and return it. 

Java
importjava.util.*;publicclassGeeks{publicstaticvoidmain(Stringargs[]){Queue<String>pq=newPriorityQueue<>();pq.add("Geeks");pq.add("For");pq.add("Geeks");System.out.println("Initial Queue: "+pq);pq.remove("Geeks");System.out.println("After Remove: "+pq);System.out.println("Poll Method: "+pq.poll());System.out.println("Final Queue: "+pq);}}

Output
Initial Queue: [For, Geeks, Geeks]After Remove: [For, Geeks]Poll Method: ForFinal Queue: [Geeks]

3. Accessing Elements

We can access the head element without removing it usingpeek() or element().

Java
importjava.util.PriorityQueue;importjava.util.Queue;publicclassGeeks{publicstaticvoidmain(String[]args){// Create a PriorityQueue of StringsQueue<String>pq=newPriorityQueue<>();// Adding elements to the queuepq.add("Geeks");pq.add("For");pq.add("Geeks");// Access the head element without removingSystem.out.println("Head using peek(): "+pq.peek());System.out.println("Head using element(): "+pq.element());// Display the queue to show elements are not removedSystem.out.println("Queue after accessing head: "+pq);}}

Output
Head using peek(): ForHead using element(): ForQueue after accessing head: [For, Geeks, Geeks]

4. Iterating the Queue

There are multiple ways to iterate through the Queue. The most famous way is converting the queue to the array and traversing using thefor loop. The queue has also an inbuilt iterator which can be used to iterate through the queue. 

Java
importjava.util.*;publicclassGeeks{publicstaticvoidmain(Stringargs[]){Queue<String>pq=newPriorityQueue<>();pq.add("Geeks");pq.add("For");pq.add("Geeks");Iteratoriterator=pq.iterator();while(iterator.hasNext()){System.out.print(iterator.next()+" ");}}}

Output
For Geeks Geeks

Methods of Queue Interface

MethodDescription
add(E e)Inserts the specified element; throws exception if insertion fails.
offer(E e)Inserts the specified element; returns false if insertion fails.
remove()Removes and returns the head of the queue; throws exception if empty.
poll()Removes and returns the head; returns null if empty.
peek()Retrieves, but does not remove, the head; returns null if empty.
size()Returns the number of elements in the queue.
isEmpty()Returns true if the queue contains no elements.
contains(Object o)Returns true if the queue contains the specified element.
iterator()Returns an iterator over the elements in the queue.
toArray()Converts the queue elements into an array.
addFirst(E e)Inserts element at the front (Deque only).
addLast(E e)Inserts element at the end (Deque only).
offerFirst(E e)Inserts element at the front; returns false if fails (Deque only).
offerLast(E e)Inserts element at the end; returns false if fails (Deque only).
removeFirst()Removes and returns the first element (Deque only).
removeLast()Removes and returns the last element (Deque only).
pollFirst()Removes and returns the first element; returns null if empty (Deque only).
pollLast()Removes and returns the last element; returns null if empty (Deque only).
getFirst()Retrieves, but does not remove, the first element (Deque only).
getLast()Retrieves, but does not remove, the last element (Deque only).
peekFirst()Retrieves, but does not remove, the first element; returns null if empty (Deque only).
peekLast()Retrieves, but does not remove, the last element; returns null if empty (Deque only).
put(E e)Inserts element, waits if necessary (BlockingQueue only).
take()Removes and returns head element, waits if empty (BlockingQueue only).



Queue in Java
Visit Courseexplore course icon
Improve
Improve

Explore

Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp