Heap data structure in java/kotlin

PriorityQueue<E> in java/kotlin is the implementation of priority heap. By default, the queued elements are ordered according to their natural ordering but a comparator can be passed to constrcutor to reverse the sorting order.

import java.util.*

fun main() {
    val minHeap = PriorityQueue<Int>() // min heap
    minHeap.add(30)
    minHeap.add(10)
    println("min value in heap: ${minHeap.poll()}") // 10

    val maxHeap = PriorityQueue<Int>(Collections.reverseOrder()) // max heap
    maxHeap.add(30)
    maxHeap.add(10)
    println("max value in heap: ${maxHeap.poll()}") // 30
}

top