0

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

2 Answers2

1

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);
Lev Leontev
  • 2,538
  • 2
  • 19
  • 31
1

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

 PriorityQueue pqmax = new PriorityQueue(arr.size(), Collections.reverseOrder()); 
 pqmax.addAll(arr);
kan
  • 28,279
  • 7
  • 71
  • 101