Search code examples
javadebuggingpriority-queuegeneric-type-argument

Lambda Function is not working in PriorityQueue Compator


I have created a Priority Queue in Java which organizes objects of type Fruit based on Double values. I used a lambda function to compare the Double value differences between two Fruit objects.

PriorityQueue<Map.Entry<Fruit, Double>> PQ = new PriorityQueue<>((a,b) -> 
(a.getValue() - b.getValue()));

I recieved the error message:

>error: incompatible types: cannot infer type arguments for PriorityQueue<>
>
>reason: cannot infer type-variable(s) E
>
>(argument mismatch; bad return type in lambda expression possibly lossy conversion from double to int)
>
>where E is a type-variable;
>
>E extends Object declared in class PriorityQueue
>

Note: I am using Java 9, so the use of lambda functions within the comparator argument for the PriorityQueue should be allowed.

Thanks!


Solution

  • A Comparator<T> lambda must return an int indicating which value is bigger, or whether they are equal. The result of subtracting two doubles is a double, not the required int. If you were comparing ints, subtracting them is a cool "trick" that works almost all the time, but not with doubles.

    You can use Double.compare, which gives you the int you need:

    PriorityQueue<Map.Entry<Fruit, Double>> PQ = new PriorityQueue<>(
        (a,b) -> Double.compare(a.getValue(), b.getValue())
    );
    

    Alternatively, create a Comparator<T> using one of those convenient methods in Comparator, rather than using a lambda:

    PriorityQueue<Map.Entry<Fruit, Double>> PQ = new PriorityQueue<>(
        Comparator.comparing(Map.Entry::getValue)
    );