Nemo_Sol Nemo_Sol - 1 month ago 13
Java Question

Java Method reference not expected here

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?

Answer

In that case, you should use a lambda, you can't apply a method reference directly:

Collections.sort(civs, 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, comparing(CivilizationUtils::getKeyExtractor));