I want to create a priority queue from an ArrayList with a custom comparator.
public PriorityQueue(Collection<? extends E> c, Comparator<? super E> comparator))
BUT there is no such constructor in PriorityQueue
I can see these constructors but haven't found a way to do it in O(n) like a heapify() would've done.
- Create a PQ with the constructor first and then add using
addAll(...).addAll()would be O(nlogn) becauseaddAll()internally callsadd()for each element of the input collection.
PriorityQueue<Foo> priorityQueue = new PriorityQueue<>(inputList.size(), comparator);
priorityQueue.addAll(inputList);
- Create PQ through Collection constructor: It doesn't have a way to set the comparator
PriorityQueue<Foo> priorityQueue = new PriorityQueue<>(inputList);