Java PriorityQueue Tutorial 🎯

beginner
18 min

Java PriorityQueue Tutorial 🎯

Welcome to our comprehensive guide on Java PriorityQueue! In this lesson, we'll explore what a PriorityQueue is, how to use it, and some practical examples to help you understand its real-world applications.

What is a PriorityQueue? 📝

A PriorityQueue is a collection of elements that can be sorted and retrieved based on their priority. It's a type of queue where the element with the highest priority is always at the front of the queue.

In Java, the PriorityQueue is an implementation of the Queue interface, which is part of the java.util package.

Why use a PriorityQueue? 💡

You might want to use a PriorityQueue when dealing with scenarios where you need to process elements based on their priority or importance, such as scheduling tasks, managing events, or implementing algorithms like Dijkstra's shortest path algorithm.

Creating a PriorityQueue ✅

To create a PriorityQueue, simply use the following code snippet:

java
import java.util.PriorityQueue; PriorityQueue<Integer> priorityQueue = new PriorityQueue<>();

In this example, we've created a PriorityQueue to store Integer values. You can also create a PriorityQueue for other data types like Strings, custom classes, and more by replacing Integer with the desired data type.

Adding Elements 📝

To add elements to a PriorityQueue, use the offer() method:

java
priorityQueue.offer(10); priorityQueue.offer(5); priorityQueue.offer(15);

The elements will be automatically sorted based on their natural ordering, with the smallest element at the front of the queue.

Retrieving Elements 📝

To retrieve the element with the highest priority (the smallest one), use the poll() method:

java
Integer polledElement = priorityQueue.poll(); // Returns 5

The poll() method removes and returns the element with the highest priority from the queue. If the queue is empty, it returns null.

Advanced Example: Top N Frequent Elements 💡

Here's a practical example of using a PriorityQueue to find the Top N frequent elements in an array:

java
import java.util.HashMap; import java.util.PriorityQueue; public class TopNElements { public static void main(String[] args) { int[] arr = {1, 3, 5, 2, 2, 3, 5, 5, 2, 4, 4}; int n = 2; HashMap<Integer, Integer> countMap = new HashMap<>(); for (int num : arr) { countMap.put(num, countMap.getOrDefault(num, 0) + 1); } PriorityQueue<Integer> priorityQueue = new PriorityQueue<>((a, b) -> countMap.get(b) - countMap.get(a)); for (int key : countMap.keySet()) { priorityQueue.offer(key); if (priorityQueue.size() > n) { priorityQueue.poll(); } } System.out.println("Top " + n + " frequent elements:"); while (!priorityQueue.isEmpty()) { System.out.print(priorityQueue.poll() + " "); } } }

This example counts the frequency of each element in an array and finds the Top N frequent elements by maintaining a PriorityQueue sorted based on the count of each element.

Quiz Time 🎯

Quick Quiz
Question 1 of 1

What is the purpose of a PriorityQueue?

Happy learning! 🎉