Java Priority Queue – How to use it

  • Post author:
  • Post category:Java
  • Post comments:0 Comments

Java Priority Queue is a data structure that is used to store a collection of elements in a way that allows efficient retrieval of the highest (or lowest) priority element. The elements in a priority queue are ordered based on their priority, which is determined by a comparator function or the natural order of the elements.

To use a priority queue in Java, you need to first import the java.util.PriorityQueue class. You can then create a new priority queue object and add elements to it. Here’s an example:

import java.util.PriorityQueue;

public class Example {
    public static void main(String[] args) {
        // create a new priority queue of integers
        PriorityQueue<Integer> queue = new PriorityQueue<>();

        // add elements to the queue
        queue.add(5);
        queue.add(3);
        queue.add(8);
        queue.add(1);

        // print the elements of the queue in order of priority
        while (!queue.isEmpty()) {
            System.out.println(queue.poll());
        }
    }
}

Output:

1
3
5
8

In the above example, we create a new PriorityQueue object of integers and add four elements to it. We then use the poll method to retrieve and remove the highest priority element from the queue, which prints the elements in ascending order.

By default, the PriorityQueue orders elements in natural order (ascending for numbers, alphabetical order for strings). However, you can also provide a custom comparator function to order elements based on a specific criteria. Here’s an example:

import java.util.PriorityQueue;
import java.util.Comparator;

public class Example {
    public static void main(String[] args) {
        // create a new priority queue of strings ordered by length
        PriorityQueue<String> queue = new PriorityQueue<>(Comparator.comparing(String::length));

        // add elements to the queue
        queue.add("apple");
        queue.add("banana");
        queue.add("orange");
        queue.add("grape");

        // print the elements of the queue in order of priority
        while (!queue.isEmpty()) {
            System.out.println(queue.poll());
        }
    }
}

Output:

apple
grape
banana
orange

In this example, we create a new PriorityQueue object of strings and provide a custom comparator function that orders elements based on their length. We then add four strings to the queue and use the poll method to retrieve and remove the highest priority element from the queue, which prints the elements in order of increasing length.

In conclusion, the Java Priority Queue is a powerful data structure that allows efficient retrieval of the highest (or lowest) priority element from a collection of elements. You can use it to store and order elements based on their priority, and even provide a custom comparator function to order elements based on a specific criteria.

Leave a Reply