简体   繁体   中英

How to implement generic Function method parameters?

Currently I have to define different methods based on the type of the Function I want to pass into the method, eg:

addCustomParameter(orderLinePrefix + "quantity=", concatenateLong(orderLines, OrderPart::getQuantity));
addCustomParameter(orderLinePrefix + "surcharge=", concatenateDouble(orderLines, OrderPart::getSurcharge));
addCustomParameter(orderLinePrefix + "dropship=", concatenateBoolean(orderLines, OrderPart::isDropship));

The methods look like this:

@Nonnull
    public <T> String concatenateBoolean(@Nonnull final Collection<T> items, @Nonnull final Function<T, Boolean> mapper)
    {
        return items.stream()
                .map(mapper)
                .map(String::valueOf)
                .collect(joining(","));
    }

    @Nonnull
    public <T> String concatenateLong(@Nonnull final Collection<T> items, @Nonnull final Function<T, Long> mapper)
    {
        return items.stream()
                .map(mapper)
                .map(String::valueOf)
                .collect(joining(","));
    }

    @Nonnull
    public <T> String concatenateDouble(@Nonnull final Collection<T> items, @Nonnull final Function<T, Double> mapper)
    {
        return items.stream()
                .map(mapper)
                .map(String::valueOf)
                .collect(joining(","));
    }

How can I refactor the above 3 methods into a single method that will accept any type and return a String?

Use a wildcard return type for the mapper:

@Nonnull
public <T> String concatenateAny(@Nonnull final Collection<T> items, @Nonnull final Function<? super T, ?> mapper)
{
    return items.stream()
            .map(mapper)
            .map(String::valueOf)
            .collect(joining(","));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM