Queue interface in Java Collection

Java provides us the Queue interface in Collection framework.

Queue supports FIFO (first-in-first-out) manner to process elements. A queue is designed to have elements inserted at the end of the queue, and elements removed from the beginning of the queue.

 

The priorityqueue class implements the Queue interface of the collection. We will implement the Queue in our example. We have many important methods in the Queue interface.

 

Methods in Queue Interface

1. add () – This method inserts an element into a queue and returns ‘true’ if the operation of adding becomes successful, otherwise displays ‘IllegalStateException’ exception.

2. remove() – This method removes the element from the top of the queue.

3. peek() – This method returns the head element(without removing it) of the queue.

 

Let’s see the implementation of Queue and uses of its methods.

Output:

Queue Contains : [Mirilla, Anshul, Edan, Matt, Abhishek, Jolly, Rubi, Knightly]
Top Element of the Queue is — Mirilla
Queue after remove operation —  [Anshul, Edan, Matt, Abhishek, Jolly, Rubi, Knightly]

 

We have implemented the Queue in above example code. Let’s understand the above code.

First, we have declared the Queue then we added elements to the queue using add() method . Then we print the queue elements.

 

Then we use the peek() method. The system prints the first inserted element because it is at the Top of the queue as It was inserted first.

Then we remove the element from the queue and again print the queue elements. Queue removed the First element and print the rest elements.

 

So we have seen FIFO(First In First Out) behavior of the queue.

 

Selenium Tutorial:

If you liked this video, then please subscribe to our YouTube Channel for more video tutorials.

0 Comment

Leave a Reply