1 回答
TA贡献1829条经验 获得超7个赞
我认为你必须编写返回类型取决于Function参数的方法:
class InputConverter<T> {
private final T value;
public InputConverter(T value) {
this.value = value;
}
public <R> R convertBy(Function<T, R> function){
return function.apply(value);
}
}
然后您可以Function使用标准方法将参数组合compose起来andThen:
final String fname = "fname_value"
InputConverter<String> inputConverter = new InputConverter<>(fname);
Function<String, List<String>> valueToListFunction = Arrays::asList;
Function<List<String>, String> firstValueFunction = l -> l.get(0);
List<String> strings = inputConverter.convertBy(valueToListFunction);//[fname_value]
String firstValue = inputConverter.convertBy(
valueToListFunction
.andThen(firstValueFunction)
);
您也可以使用其他标准FunctionalInterfaces,例如UnaryOperator:
UnaryOperator<String> firstChangeFunction = arg -> arg.concat(" + first");
UnaryOperator<String> secondChangeFunction = arg -> arg.concat(" + second");
String firstValue = inputConverter.convertBy(
valueToListFunction
.andThen(firstValueFunction)
.andThen(secondChangeFunction)
.compose(firstChangeFunction)
); // sout: fname_value + first + second
或者自己写。
添加回答
举报