How to Convert an ArrayList and an Array into a PriorityQueue in Java?
Last Updated :
14 Feb, 2024
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);
Program to Convert an ArrayList into a PriorityQueue in Java
Below is the implementation to convert an ArrayList into a PriorityQueue Java.
Java
import java.util.ArrayList;
import java.util.PriorityQueue;
public class Main {
public static void main(String[] args)
{
ArrayList<String> courseList = new ArrayList<>();
courseList.add( "C++" );
courseList.add( "Java" );
courseList.add( "Python" );
PriorityQueue<String> queue
= new PriorityQueue<>(courseList);
for (String str : queue) {
System.out.print(str + " " );
}
}
}
|
Explanation of above code:
- An ArrayList of courses created.
- Then it converted to PriorityQueue using constructor.
- For-each loop iterates PriorityQueue.
- Elements printed separated by space.
Syntax of converting an Array into a PriorityQueue:
T[] array = { /* elements of the arary */ };
PriorityQueue<T> priorityQueue = new PriorityQueue<>(Arrays.asList(array));
Program to Convert an Array into a PriorityQueue in Java
Below is the implementation to convert an Array into a PriorityQueue Java
Java
import java.util.Arrays;
import java.util.PriorityQueue;
public class Main {
public static void main(String[] args)
{
String[] courseArray = { "C++" , "Java" , "Python" };
PriorityQueue<String> queue = new PriorityQueue<>(
Arrays.asList(courseArray));
for (String str : queue) {
System.out.print(str + " " );
}
}
}
|
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.
Share your thoughts in the comments
Please Login to comment...