user1224441
user1224441

Reputation:

Can I create a Comparator object from a lambda expression without explicit variable?

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.

Upvotes: 4

Views: 236

Answers (3)

shmosel
shmosel

Reputation: 50716

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));

Upvotes: 2

Ousmane D.
Ousmane D.

Reputation: 56423

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.

Upvotes: 1

rgettman
rgettman

Reputation: 178263

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));

Upvotes: 2

Related Questions