如果您想创建一个应用多个函数并且对中间值不感兴趣的方法,您可以将其设为通用方法。你问题中的代码很奇怪,因为它假设value
可以是一个String
and a List<String>
同时。
但与你的另一个问题 https://stackoverflow.com/q/33298519/2711488,有不同的画面。虽然 varargs 方法不能以这种方式工作,但您可以轻松地为实际用例提供重载方法:
public class InputConverter<T> {
private T value;
public InputConverter(T value) {
this.value = value;
}
public <R> R convertBy(Function<? super T, ? extends R> f) {
return f.apply(value);
}
public <T1,R> R convertBy(
Function<? super T, ? extends T1> f1, Function<? super T1, ? extends R> f2) {
return f2.apply(f1.apply(value));
}
public <T1,T2,R> R convertBy(
Function<? super T, ? extends T1> f1, Function<? super T1, ? extends T2> f2,
Function<? super T2, ? extends R> f3) {
return f3.apply(f2.apply(f1.apply(value)));
}
public <T1,T2,T3,R> R convertBy(
Function<? super T, ? extends T1> f1, Function<? super T1, ? extends T2> f2,
Function<? super T2, ? extends T3> f3, Function<? super T3, ? extends R> f4) {
return f4.apply(f3.apply(f2.apply(f1.apply(value))));
}
}
假设您修复了接口类型并创建了函数,如中所述这个答案 https://stackoverflow.com/a/33300743/2711488,你可以像这样使用它
InputConverter<String> fileConv=new InputConverter<>("LamComFile.txt");
List<String> lines = fileConv.convertBy(flines);
String text = fileConv.convertBy(flines, join);
List<Integer> ints = fileConv.convertBy(flines, join, collectInts);
Integer sumints = fileConv.convertBy(flines, join, collectInts, sum);