I have a List called "racers" of simple class
class Racer {
private String name;
private String teamName;
// and getters
}
I am using а method to find maximum lengths of the fields in the list:
int maxRacerNameLength = getMaxFieldLength(racers, Racer::getName);
int maxTeamNameLength = getMaxFieldLength(racers, Racer::getTeamName);
Method implementation:
private int getMaxFieldLength(List<Racer> racers, Function<Racer, String> getter) {
return racers.stream().mapToInt(racer -> getter.apply(racer).length()).max().getAsInt();
}
How do I get rid of this last lambda using method reference?
You can do it by breaking mapToInt(racer->getter.apply(racer).length())
into two steps:
return racers.stream().map(getter::apply).mapToInt(String::length).max().getAsInt();
Demo:
public class Main {
public static void main(String[] args) {
List<Racer> racers = List.of(
new Racer("Andy", "One"),
new Racer("Thomas", "Four"),
new Racer("John", "One"),
new Racer("Newton", "Four")
);
System.out.println(getMaxFieldLength(racers, Racer::getName));
System.out.println(getMaxFieldLength(racers, Racer::getTeamName));
}
static int getMaxFieldLength(List<Racer> racers, Function<Racer, String> getter) {
return racers.stream().map(getter::apply).mapToInt(String::length).max().getAsInt();
}
}
Output:
6
4
Kind | Example |
---|---|
Reference to a static method | ContainingClass::staticMethodName |
Reference to an instance method of a particular object | containingObject::instanceMethodName |
Reference to an instance method of an arbitrary object of a particular type | ContainingType::methodName |
Reference to a constructor | ClassName::new |
Learn more about it from Method References.