How exactly do you chain method references for instances with Java 8? Example:
Collections.sort(civs,Comparator.comparing(Civilization::getStrategy.getStrategLevel));
getStrategy
of a Civilization
instance returns a Strategy
object instance which has the instance method getStrategyLevel
.
Why doesn't the Comparator.comparing
method return a comparator with it's functional interface implemented by the lambda expression?
In that case, you should use a lambda, you can't apply a method reference directly:
Collections.sort(civs, Collectors.comparing(c -> c.getStrategy().getStrategLevel()));
Though, there is a way to use a method reference here. Assuming that you have a class like
class CivilizationUtils {
public static Integer getKeyExtractor(Civilization c) {
return c.getStrategy().getStrategLevel();
}
}
the issue could be solved like
Collections.sort(civs, Collectors.comparing(CivilizationUtils::getKeyExtractor));
You cannot do it with a method reference, you need to use a lambda expression or create a static method.
There are four kinds of method references:
ContainingClass::staticMethodName
containingObject::instanceMethodName
ContainingType::methodName
ClassName::new
More details about method reference
.
So here, with a lambda expression
it would be:
Collections.sort(civs, Comparator.comparing(c -> c.getStrategy.getStrategLevel()));
Or in case you create a static method
public static int getStrategLevel(Civilization c) {
return c.getStrategy().getStrategLevel();
}
Then your code would be:
Collections.sort(civs, Comparator.comparing(MyClass::getStrategLevel));
Collections.sort(civs,Comparator.comparing(civ -> civ.getStrategy().getStrategLevel()));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With