Open In App

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

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

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:

  • retainAll( ): This is a pre-defined method, and it returns the common elements of the two priority queues.
  • addAll(): This is also a pre-defined method, and it returns the addition of elements of the two priority queues.

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

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:

  • In the above program, we have created two PriorityQueues. First one is queue1 and the second one is queue2.
  • The intersection is obtained by creating a new PriorityQueue (intersection) and retaining only the common elements.
  • The union is obtained by creating another new PriorityQueue (union) and adding all elements from both queues.
  • At last, the program prints the results.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads