How to combine similar methods?

Parazit-nsk :

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);
    }
kaya3 :

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.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=418350&siteId=1