Program to Convert an Array into a PriorityQueue in Java
Below is the implementation to convert an Array into a PriorityQueue Java
Java
// Java Program to Convert an Array into a PriorityQueue import java.util.Arrays; import java.util.PriorityQueue; public class Main { public static void main(String[] args) { // create an Array String[] courseArray = { "C++" , "Java" , "Python" }; // convert Array to PriorityQueue PriorityQueue<String> queue = new PriorityQueue<>( Arrays.asList(courseArray)); // print PriorityQueue for (String str : queue) { System.out.print(str + " " ); } } } |
Output
C++ Java Python
Explanation of above code:
- The array of strings {“C++”, “Java”, “Python”} is converted to a PriorityQueue using Arrays.asList().
- A PriorityQueue orders elements in ascending natural order by default.
- So, when iterating over the PriorityQueue, the elements will be in order of their ASCII values – “C++”, “Java”, “Python”.
- Therefore, the output printed will be: C++ Java Python.
How to Convert an ArrayList and an Array into a PriorityQueue in Java?
A priority queue is a special type of queue that orders elements based on their priority. Elements with higher priority are dequeued before lower-priority elements. PriorityQueue uses a heap data structure internally to provide efficient O(log n) time for enqueue and dequeue operations.
In this article, we will learn how to convert an ArrayList and an Array into a PriorityQueue in Java.
Syntax of converting an ArrayList into a PriorityQueue:
ArrayList<T> arrayList = new ArrayList<>();
PriorityQueue<T> priorityQueue = new PriorityQueue<>(arrayList);
Contact Us