Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 531
Nemo_Sol Avatar asked Nov 05 '16 16:11

Nemo_Sol


3 Answers

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));
like image 157
Andrew Tobilko Avatar answered Nov 12 '22 23:11

Andrew Tobilko


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:

  1. Reference to a static method like ContainingClass::staticMethodName
  2. Reference to an instance method of a particular object like containingObject::instanceMethodName
  3. Reference to an instance method of an arbitrary object of a particular type like ContainingType::methodName
  4. Reference to a constructor like 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));
like image 33
Nicolas Filotto Avatar answered Nov 12 '22 23:11

Nicolas Filotto


Collections.sort(civs,Comparator.comparing(civ -> civ.getStrategy().getStrategLevel()));
like image 1
Shashank Avatar answered Nov 12 '22 22:11

Shashank