Program to Convert a PriorityQueue into a Set in Java
Java
// Java program to convert a PriorityQueue into a Set import java.util.HashSet; import java.util.PriorityQueue; import java.util.Set; public class PriorityQueueToSet { 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 a Set Set<Integer> set = new HashSet<>(priorityQueue); // Print the elements in the Set System.out.println( "Set elements are: " +set); } } |
Output
Set elements are: [1, 2, 3, 4]
Explanation of the Program:
- The above Java program is the example of the converting the PriorityQueue into the set using Set Interface.
- Once it converted into the Set then print the resultant set.
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.
Contact Us