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

I am not familiar with the lambda expression in Java yet.

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

written without explicitly creating a variable compareDouble?

I tried the following, but why doesn't it work?

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

Thank.

+4
source share
3 answers

First, your immediate mistake: you forgot to place parentheses around your type of casting. 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.

In addition, Java type inference will work without explicitly casting your lambda expression to the required functional type. Try:

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

, , :

Collections.sort(testList, Collections.reverseOrder(Double::compare));
+2

Double Comparable, zero-arg reverseOrder():

testList.sort(Collections.reverseOrder());

:

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

Id - :

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

Type - , getDoubleValue - double, .

.

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

, . , :

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

.

, compareDouble reverseOrder.

+1

Source: https://habr.com/ru/post/1689797/


All Articles