2
Collections.sort(employees, (employee1, employee2) -> {
    return (employee1.getAge() >= employee2.getAge()) ? -1 : 1;
});

The above code sample sorts the 'employees' List according to age just fine. But, the code below gives an error.

Collections.sort(employees, (employee1, employee2) ->
    employee1.getAge() >= employee2.getAge() ? -1 : 1;
);

Isn't the ternary operator considered as a single line expression? The error shown is:

java: ')' expected; java: illegal start of expression

  • Your comparison expression is not correct. It gives the wrong output if the elements are equal. – user207421 Jun 05 '21 at 06:55
  • And there is no such thing in Java as a 'single line expression', and nothing about it in the error message. – user207421 Jun 05 '21 at 07:25
  • @user207421 I think because of '>=' it won't give the wrong output if the elements are equal. And actually, I didn't know the exact words to frame it so I used 'single line expression' – user13081445 Jun 05 '21 at 07:43
  • You are mistaken. It is required to return zero if the elements are equal. – user207421 Jun 05 '21 at 08:06

1 Answers1

4

Syntactically, the lambda body (the thing after ->) is either a block or an expression.

If it's a block, then it must contain zero or more statements. The return statement ends with a ;, which is why ; is needed in the first case.

In the second case, you attempted to write a conditional expression ("ternary operator"), but as you can see in the syntax, the trailing ; is not part of a conditional expression, (AFAIK, no expression ends with a ;) so you've written something extra that the parser didn't expect, which causes the code to not compile.

So you should delete the ;:

Collections.sort(employees, (employee1, employee2) ->
    employee1.getAge() >= employee2.getAge() ? -1 : 1
);

Also, note that this implementation of Comparator does not ensure that sgn(compare(x, y)) == -sgn(compare(y, x)) for all x and y, which is part of the contract of Comparator.compare. sort will not work correctly.

Sweeper
  • 213,210
  • 22
  • 193
  • 313