Open In App

How to Copy Elements from One PriorityQueue to Another in Java?

Last Updated : 27 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In Java, a priority queue is a data structure that allows the users to store data based on their priority. In this article, we will learn how to copy elements from one priority queue to another in Java.

Example

Input: PriorityQueue original ={1,2,3,4,5}
Output: PriorityQueue Copy ={1,2,3,4,5}

Copy elements from One PriorityQueue to Another

To copy elements from one Priority Queue to another in Java, we can use the addAll Method. Following is the syntax to use the addAll method in Java:

Syntax for addAll method

destinationPq.addAll(sourcePq);

Parameters

  • sourcePq: is the name of the original priority queue.
  • destinationPq: is the name of the priority queue where you want to copy the elements.

Java Program to Copy Elements from One PriorityQueue to Another

The following program illustrates how we can copy elements from one priority queue to another in Java:

Java
// Java Program to Copy Elements from
// One PriorityQueue to Another
import java.util.PriorityQueue;

// Main Class
public class Main {
    public static void main(String[] args) {
        // Creating  priority queue of integers
        PriorityQueue<Integer> sourcePq = new PriorityQueue<>();
        
        // Creating another priority queue to copy
          // elements from the original priorityQueue
        PriorityQueue<Integer> destinationPq = new PriorityQueue<>();
        
        // Adding elements to the original priority queue
        sourcePq.add(1);
        sourcePq.add(2);
        sourcePq.add(3);
        sourcePq.add(4);
        sourcePq.add(5);
        
        // Copying elements from source priorityQueue to it's copy
        destinationPq.addAll(sourcePq);
        
        // Printing the elements of the original priority queue
        System.out.println("Original Priority Queue: " + destinationPq);
        
        // Printing the elements of the copied priority queue
        System.out.println("Copied Priority Queue: " + destinationPq);
    }
}

Output
Original Priority Queue: [1, 2, 3, 4, 5]
Copied Priority Queue: [1, 2, 3, 4, 5]

Complexities:

Time Complexity: O(N), where N is the length of the priority queue.
Auxiliary Space: O(N)


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads