VOOZH about

URL: https://www.geeksforgeeks.org/java/how-to-copy-elements-from-one-priorityqueue-to-another-in-java/

⇱ How to Copy Elements from One PriorityQueue to Another in Java? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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

Last Updated : 23 Jul, 2025

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:


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)

Comment