Open In App

How to Perform Range Queries on a PriorityQueue in Java?

Last Updated : 14 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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




// 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:

  • We have created a PriorityQueue named pq to store integers.
  • We have added elements to the PriorityQueue using the offer() method.
  • Then we define the minimum and maximum values of the range you want to query.
  • After that we iterate through the PriorityQueue, removing elements until you reach the minimum value of the range.
  • After reaching the minimum value, iterate through the remaining elements in the PriorityQueue, printing those that are within the specified range.

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.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads