I have quite the same methods, but for different fields of class. How can I make a method that will do both of these things, depending on parameters.
Thanks in advance.
private int getLengthOfLongestName(List<Driver> drivers) {
return drivers.stream()
.map(t -> t.getName())
.max(Comparator.comparingInt(String::length))
.map(String::length)
.orElse(0);
}
private int getLengthOfLongestTeam(List<Driver> drivers) {
return drivers.stream()
.map(t -> t.getTeamName())
.max(Comparator.comparingInt(String::length))
.map(String::length)
.orElse(0);
}
Take a Function
as a parameter:
private int getLengthOfLongest(List<Driver> drivers, Function<Driver, String> func) {
return drivers.stream()
.map(func)
.mapToInt(String::length)
.max()
.orElse(0);
}
Then you can call it like getLengthOfLongest(driverList, Driver::getName)
, or use Driver::getTeamName
for the other version.
Note that it's a bit simpler to mapToInt
to the string lengths before taking the max
, as this avoids taking the string length twice, and then you have an IntStream
so you don't need to provide an explicit comparator.
I would also recommend using a method reference like Driver::getName
instead of a lambda like t -> t.getName()
as this makes it more explicit what type of thing you are getting the name of.