Open In App

How to Perform Range Queries on a PriorityQueue in Java?

Based on a priority heap, a Java PriorityQueue represents an unlimited priority queue. PriorityQueue does not directly handle range queries, but it does provide quick access to the element with the greatest priority. On the other hand, range queries may be executed by taking pieces from the PriorityQueue that fall within a certain range.

In this article, we will learn how to perform range queries on a PriorityQueue in Java.



Way to Perform Range Queries on a PriorityQueue

To retrieve entries from a PriorityQueue that fall within a certain range, we can use a range query. We can loop over the PriorityQueue and filter entries according to the range criterion to do this.

Program to Perform Range Queries on a PriorityQueue in Java

Let’s construct an example in which we execute range queries on an integer containing PriorityQueue.






// Java program to perform range queries on a PriorityQueue
import java.util.PriorityQueue;
public class RangeQuery 
{
    public static void main(String[] args) 
    {
          // Create a PriorityQueue
        PriorityQueue<Integer> pq = new PriorityQueue<>();    
          
          // Add elements to the PriorityQueue
        pq.offer(4);
        pq.offer(6);
        pq.offer(8);
        pq.offer(10);
        pq.offer(12);
        pq.offer(14);
  
        // Define the range
        int minRange = 8;
        int maxRange = 14;
  
        // Perform the range query
        System.out.println("Elements within the range " + minRange + " and " + maxRange + ":");
  
        // Remove elements until reaching the minimum value
        while (!pq.isEmpty() && pq.peek() < minRange) {
            pq.poll();
        }
  
        // Print elements within the range
        while (!pq.isEmpty() && pq.peek() <= maxRange) {
            System.out.println(pq.poll());
        }
    }
}

Output
Elements within the range 8 and 14:
8
10
12
14

Explanation of the above program:

Note: PriorityQueue does not support direct range queries. So, we have removed elements until reaching the minimum value and then printing elements within the range.


Article Tags :