4

I am not yet familiar with lambda expression in Java.

Can

//create a comparator object using a Lambda expression
Comparator<Double> compareDouble = (d1, d2) -> d1.compareTo(d2);

//Sort the Collection in this case 'testList' in reverse order
Collections.sort(testList, Collections.reverseOrder(compareDouble));

be written without explicitly create a variable compareDouble?

I tried the following, but why does it not work?

//Sort the Collection in this case 'testList' in reverse order
Collections.sort(testList, Collections.reverseOrder(new Comparator<Double> ((d1, d2) -> d1.compareTo(d2))));

Thanks.

2

3 Answers 3

2

First, your immediate error: You forgot to place parentheses around your casting type. Try:

Collections.sort(testList, Collections.reverseOrder( (Comparator<Double>) ((d1, d2) -> d1.compareTo(d2))));

Edit: The above error was when the question didn't have new so it looked like a cast.

Also, Java's type inference will work without explicitly casting your lambda expression to the necessary functional type. Try:

Collections.sort(testList, Collections.reverseOrder( (d1, d2) -> d1.compareTo(d2) ));

When the comparison operation already exists as in this case, you can make it even simpler with a method reference:

Collections.sort(testList, Collections.reverseOrder(Double::compare));
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. I forgot to type in new to invoke constructor, and didn't intend to use casting. Why doesn't new work?
When you're using new, you're attempting to create a new instance of something directly, but Comparator is an interface. The lambda expression itself is sufficient code.
@rgettman Double already implements Comparable, a simple Collections.sort(testList, Collections.reverseOrder()) will do
2

Double already implements Comparable, so you can use the zero-arg reverseOrder() overload:

testList.sort(Collections.reverseOrder());

Or you can reverse your custom comparator:

testList.sort((d1, d2) -> d2.compareTo(d1));

Comments

1

I’d go with something like:

Collections.sort(testList, Comparator.comparingDouble(Type::getDoubleValue).reversed());

Where Type is the name of your class and getDoubleValue is the double value being used as the sort key.

Another shorter alternative.

testList.sort(Comparator.comparingDouble(Type::getDoubleValue).reversed());

edit

I think I’ve misinterpreted your current problem. Nevertheless, altering your current solution to:

Collections.sort(testList, Collections.reverseOrder((e, a) -> e.compareTo(a)));

Would suffice.

It’s just a matter of taking the behavior you’ve assigned to the variable compareDouble and directly pass it into the reverseOrder method.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.