Search code examples
javapriority-queue

Java Priority Queue heapify


In general, if I understand correctly, there is a difference of runtime between "heapifying;o(n)" a given list vs adding each individual element; o(lg n). Does java follow this behavior? If not below question may not be valid.

The below example appears to create a "min-heap".

List<Integer> myList = List.of(4,3,10,1);
PriorityQueue<Integer> queue = new PriorityQueue<>(myList);

However, let say if I want to build a "max heap", but the constructor does not let me pass in a collection and comparator together. In this case, is the only to build max heap is via creating a wrapper class that implements comparable?

 class Wrapper implements Comparable<Wrapper> {
 ...
 @Override
 int compareTo(Wrapper o) {// define rule here...}
 }

 List<Integer> val = List.of(5,3,2,10);
 List<Wrapper> wrappedVal = val.stream().map(Wrapper::new).collect(Collectors.toList());

 PriorityQueue<Wrapper> queue = new PriorityQueue<>(wrappedVal); 

Note: I understand that it is possible to create priority queue with a comparator, then repeatedly call add.


Solution

  • However, let say if I want to build a "max heap", but the constructor does not let me pass in a collection and comparator together. In this case, is the only to build max heap is via creating a wrapper class that implements comparable?

    Yes. This class does not provide a constructor that can pass in a collection and a comparator at the same time. It will use the compareTo method of the collection element, so as you did, you need a Wrapper(But this may seem a little unnecessary?).

    repeatedly call add.

    You can use PriorityQueue#addAll().