Uddhav Navneeth
Uddhav Navneeth

Reputation: 11

How to convert an arraylist to a max heap in java using priority queue

I know we can create a max heap using priority queue using Collections.reverseOrder(), but I need to pass the ArrayList in that place also. I tried to create a custom comparator just in case, but it doesnt seem to work. I would like to know the exact syntax of doing so.
Example/My knowledge:
1)creating an empty min heap -> PriorityQueue pqmin = new PriorityQueue();
2)Creating a min heap from an ArrayList arr -> PriorityQueue pqmin = new PriorityQueue(arr);
3)Creating an empty max heap -> PriorityQueue pqmax = new PriorityQueue(Collections.reverseOrder());

My question: How to create max heap from existing arrayList using priorityQueue in Java

Upvotes: 0

Views: 1175

Answers (2)

kan
kan

Reputation: 28951

Use the 3), then addAll. Or slightly better is to pass initial capacity

 PriorityQueue pqmax = new PriorityQueue(arr.size(), Collections.reverseOrder()); 
 pqmax.addAll(arr);

Upvotes: 2

Lev Leontev
Lev Leontev

Reputation: 2615

There's no such constructor in PriorityQueue that takes both a collection and a comparator.

But you can use addAll method:

PriorityQueue pqmax = new PriorityQueue(Collections.reverseOrder());
pqmax.addAll(arr);

Upvotes: 1

Related Questions