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!
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.
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.
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.
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.
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)));
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With