Search code examples
javacomparatorpriority-queueheap

Why is this lambda expression not working for defining this comparator?


I want to create a min-heap where the elements are pairs of integers and I want the heap to compare the first number in the pair. I am defining it like so:

PriorityQueue<List<Integer>> heap = new PriorityQueue((a, b) -> a.get(0) - b.get(0));

However, this causes these errors:

ERROR!
javac /tmp/1YraTeGijp/HelloWorld.java
/tmp/1YraTeGijp/HelloWorld.java:7: error: cannot find symbol
PriorityQueue<List<Integer>> heap = new PriorityQueue((a, b) -> a.get(0) - b.get(0));
                                                                         ^
  symbol:   method get(int)
  location: variable a of type Object
/tmp/1YraTeGijp/HelloWorld.java:7: error: cannot find symbol
        PriorityQueue<List<Integer>> heap = new PriorityQueue((a, b) -> a.get(0) - b.get(0));
^
  symbol:   method get(int)
  location: variable b of type Object
Note: /tmp/1YraTeGijp/HelloWorld.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

I tried using types when defining the a and b parameters but that also raised errors. Whats the fix?


Solution

  • If you use an IDE, you should see the following warning :

    PriorityQueue is a raw type. References to generic type PriorityQueue should be parameterized

    You are missing <List<Integer>> or simply <> after new PriorityQueue :

    PriorityQueue<List<Integer>> heap = new PriorityQueue<>((a, b) -> a.get(0) - b.get(0));