Program to Convert a PriorityQueue into an Array in Java
Java
// Java Program to Convert a PriorityQueue into an Array import java.util.PriorityQueue; public class GfGPriorityQueueToArray { // Main method public static void main(String[] args) { // Create a PriorityQueue PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(); priorityQueue.add( 3 ); priorityQueue.add( 1 ); priorityQueue.add( 4 ); priorityQueue.add( 2 ); // Convert PriorityQueue to an array Integer[] array = priorityQueue.toArray( new Integer[ 0 ]); // Print the elements in the array System.out.println( "Array Elements are:" ); for (Integer element : array) { System.out.println(element); } } } |
Array Elements are: 1 2 4 3
Explanation of the Program:
The above Java program is the example of the converting the PriorityQueue into the array using toArray() method. Once it converted into an array, traverse the elements, and then print the elements.
- toArray(): This is a common method that can be used to convert another form object into the array object, and it’s returned the array objects.
Approach to convert a PriorityQueue into a List:
- First, create the class named GfGPriorityQueueToList and define the main method.
- In main method, create one integer priority queue using the PriorityQueue.
- Adding the elements of the two priority queues.
- Create the one list using List.
- After that add the priority queue into the list.
- Print the results list.
How to Convert a PriorityQueue into an Array, List, and Set in Java?
In Java, PriorityQueue is an implementation of the Queue interface. It means high-priority elements can be saved first compared to lower-priority elements in the queue, and it follows the natural order of elements.
In this article, we will learn how to convert a PriorityQueue into an Array, List, and Set in Java.
Approach to convert a PriorityQueue into an Array:
- First, create the class named GfGPriorityQueueToArray and define the main method.
- In the main method, create one integer priority queue using the PriorityQueue.
- Adding the elements of the two-priority queue.
- Using toArray() method to convert the priority queue to an array.
- Print the results array using a for loop traversal array and print the elements.