Nemo_Sol Nemo_Sol - 1 year ago 127
Java Question

Java Method reference not expected here

How exactly do you chain method references for instances with Java 8? Example:


of a
instance returns a
object instance which has the instance method

Why doesn't the
method return a comparator with it's functional interface implemented by the lambda expression?

Answer Source

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));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download