javaheappriority-queuemin-heap

Priority Queue of an array of integers in java


I want to compare the second element of the following array:

int[][] intervals = new int[][]{new int[]{0, 30},new int[]{5, 10},new int[]{15, 20}};

My priority queue with custom comparator:

PriorityQueue<int[]> heap = new PriorityQueue(intervals.length, (a, b) -> a[1] - b[1]);

But I get the below 2 errors:

Line 8: error: array required, but Object found
        PriorityQueue<Integer[]> heap = new PriorityQueue(intervals.length, (a, b) -> a[1] - b[1]);
                                                                                       ^
Line 8: error: array required, but Object found
        PriorityQueue<Integer[]> heap = new PriorityQueue(intervals.length, (a, b) -> a[1] - b[1]);
                                                                                             

Solution

  • You could use Integer.compare

    PriorityQueue<int[]> heap = new PriorityQueue<>(intervals.length, (a,b) -> Integer.compare(a[1],b[1]));