Java lambda expression: incompatible type: error return type in lambda expression
•
Java
I have the following worklists, each of which is a list of profits and difficulties:
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 according to their profit (the first element of each job), as follows:
jobs.sort((j1,j2) -> j1.get(0) > j2.get(0));
However, the following errors were obtained:
error: incompatible types: bad return type in lambda expression
What did I do wrong and how should I solve this problem? thank you!
Solution
Your comparator is invalid because it returns a Boolean value and the expected return type is an int
A simple solution is:
jobs.sort(Comparator.comparing(e -> e.get(0)));
or
jobs.sort((j1,j2) -> Integer.compare(j1.get(0),j2.get(0)));
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码