Java Queue

By | September 29, 2021
Java Queue

Introduction

In Java, Queues are used for pushing in data and retrieving it later. Queue follows the principle of FIFO i.e. First In First Out. In this article, we will discuss the most important methods of Java Queues and give a good amount of Java Queue examples to further the learning process.

How to use Java Queue: Examples

Queue is an ordered list of java objects where elements can be added at the end of the queue and removed from the first. The insertion order is not necessarily retained. Queue is an interface so to use the methods, we need a class that implements these methods. The most common classes that use Queue are LinkedList and PriorityQueue. To create a queue object, use the add method. To remove the head, we can use poll() or remove() methods. Here is a Java Queue example that shows adding and removing queue operations:

Queue<String> qSample = new PriorityQueue<String>();

//Lets add some elements

qSample.add("one");
qSample.add("one");
qSample.add("two");
qSample.add("three");
qSample.add("four");
qSample.add("five");

System.out.println("Queue elements: " + qSample);
System.out.println("initial Q size: "+qSample.size());

// view the head of the queue

System.out.println(qSample.peek());

//view and remove the head of the queue

System.out.println(qSample.poll());
System.out.println("q size: " + qSample.size());
System.out.println("Queue elements after removing head: " + qSample);

//To remove a particular item, use the remove method

System.out.println("Removing duplicate entry...." + qSample.remove("one"));

// we can also remove the head using remove() without any parameter

System.out.println("Removing head using remove()...." + qSample.remove());
System.out.println("Final Queue elements: " + qSample);

Note that we can do the same operations with LinkedList as well. Now, let us see how we can iterate through the Java Queue items.

qSample.add("six");
qSample.add("four");
qSample.add("five");

Iterator<String> qItr = qSample.iterator();

while(qItr.hasNext())
System.out.println(qItr.next());

Note that we have to import the following for the program to run:

import java.util.Iterator;
import java.util.PriorityQueue;
import java.util.Queue;

Conclusion

In this article, we have discussed the basic queue operations. Both PriorityQueue and LinkedList are not thread-safe, hence we can also use PriorityBlockingQueue, which is an unbounded Queue. Due to this, Blocking queues may throw OutOfMemory errors if the resources are exhausted.

People are also reading: 

Leave a Reply

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