Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Lambda Expression: incompatible types: bad return type in lambda expression

I have the following list of jobs, each element is a list containing profit and difficulty:

List<List<Integer>> jobs = new ArrayList<>();
for (int i = 0; i < difficulty.length; i++) {
    List<Integer> job = new ArrayList<Integer>();
    job.add(profit[i]);
    job.add(difficulty[i]);
    jobs.add(job);
}

Now I want to sort the jobs based on their profit (first element of each job) like below:

jobs.sort((j1, j2) -> j1.get(0) > j2.get(0));

But got the following error:

error: incompatible types: bad return type in lambda expression

What did I do wrong and how do I fix this? Thanks!

like image 422
Edamame Avatar asked Apr 29 '18 20:04

Edamame


People also ask

Can lambda expressions be stored in variables in Java?

Lambda expressions can be stored in variables if the variable's type is an interface which has only one method. The lambda expression should have the same number of parameters and the same return type as that method. Java has many of these kinds of interfaces built in, such as the Consumer interface (found in the java.util package) used by lists.

How lambda expression works with the return statements?

As you know Lambda expression supported the Functional interface. It creates a reference for the interface and provides the body with the abstract method. We have seen many examples with a lambda expression. Now we will discuss how Lambda expression works with the return statements.

Why Java compiler does not create class for lambda expression?

Java lambda expression is treated as a function, so compiler does not create .class file. Lambda expression provides implementation of functional interface. An interface which has only one abstract method is called functional interface.

What is argument list in lambda expression in Java?

Java Lambda Expression Syntax 1 Argument-list: It can be empty or non-empty as well. 2 Arrow-token: It is used to link arguments-list and body of expression. 3 Body: It contains expressions and statements for lambda expression.


2 Answers

Your comparator is invalid as it returns a boolean whereas the expected return type is an int.

A simple solution would be:

jobs.sort(Comparator.comparing(e -> e.get(0)));

or:

jobs.sort((j1, j2) -> Integer.compare(j1.get(0), j2.get(0)));
like image 66
Ousmane D. Avatar answered Oct 06 '22 15:10

Ousmane D.


The problem is in following line

jobs.sort((j1, j2) -> j1.get(0) > j2.get(0));

is that you don't follow signature of sort method:

default void sort(Comparator<? super E> c)

When you implement comparator as lambda, you should pass lambda that returns int, not boolean.

in your case it should be smth like this:

jobs.sort((j1, j2) -> compare two lists somehow to return int);

or use snippet that @Aominè provided

like image 2
Oleg Zinoviev Avatar answered Oct 06 '22 15:10

Oleg Zinoviev