当前,我必须根据要传递给方法的Function
的类型定义不同的方法,例如:
addCustomParameter(orderLinePrefix + "quantity=", concatenateLong(orderLines, OrderPart::getQuantity));
addCustomParameter(orderLinePrefix + "surcharge=", concatenateDouble(orderLines, OrderPart::getSurcharge));
addCustomParameter(orderLinePrefix + "dropship=", concatenateBoolean(orderLines, OrderPart::isDropship));
方法如下:
@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(","));
}
如何将上述3种方法重构为可以接受任何类型并返回String的单个方法?
答案 0 :(得分:3)
为映射器使用通配符返回类型:
@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(","));
}