Open In App

How to Find the Intersection and Union of Two PriorityQueues in Java?

In Java, PriorityQueue is an implementation of the Queue Interface. It can be used to provide a way to store the elements in a queue based on their priority basis. This means high-priority elements can store first compared to lower-priority elements in the queue.

In this article, we will be learning how to find the intersection and union of two PriorityQueues in Java.



Methods to Implement the Intersection and Union

To implement the intersection and union logic using the two methods are depicted below:

Program to Find the Intersection and Union of Two PriorityQueues in Java




// Java Program to find the intersection and union of two PriorityQueues 
import java.util.PriorityQueue;
public class GfGPriorityQueue 
{
   //Main method
    public static void main(String[] args) 
    {
        // create two PriorityQueues
        PriorityQueue<Integer> queue1 = new PriorityQueue<>();
        PriorityQueue<Integer> queue2 = new PriorityQueue<>();
  
        // Populate the queues
        queue1.add(1);
        queue1.add(3);
        queue1.add(5);
  
        queue2.add(3);
        queue2.add(4);
        queue2.add(5);
  
        // Find intersection
        PriorityQueue<Integer> intersection = new PriorityQueue<>(queue1);
        intersection.retainAll(queue2);
  
        System.out.println("Intersection of the two priorityQueues: " + intersection);
  
        // Find union
        PriorityQueue<Integer> union = new PriorityQueue<>(queue1);
        union.addAll(queue2);
  
        System.out.println("Union of the two priorityQueues: " + union);
    }
}

Output

Intersection of the two priorityQueues: [3, 5]
Union of the two priorityQueues: [1, 3, 5, 3, 4, 5]



Explanation of the Program:


Article Tags :