Reputation: 21
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);
}
Upvotes: 1
Views: 119
Reputation: 40048
You can pass Function
as parameter to getLongestValue
and just use max
to get maximum value
private int getLongestValue(List<Driver> drivers, Function<Driver, String> func) {
return drivers.stream()
.map(func)
.mapToInt(String::length)
.max()
.orElse(0);
}
So you can use it for mapping different values
getLongestValue(list, Driver::getName)
getLongestValue(list, Driver::getTeamName)
Upvotes: 3
Reputation: 51034
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.
Upvotes: 11