1

我有一个方法:

public List<Integer> convertBy(Function<String, List<String>> flines, Function<List<String>, String> join, Function<String, List<Integer>> collectInts) {
    return collectInts.apply(join.apply(flines.apply((String) value)));
}//first method

public Integer convertBy(Function<List<String>, String> join, Function<String, List<Integer>> collectInts, Function<List<Integer>, Integer> sum) {
    return sum.apply(collectInts.apply(join.apply((List<String>) value)));
}//second method

尽管它们的参数是用不同类型参数化的,但我不能重载第一种方法。我可能会使用不同的界面,Function<T,R>但不知道哪一个就足够了,因为我浏览了它们的列表并且找不到一个https://docs.oracle.com/javase/8/docs/api/java/ util/function/package-summary.html

这些函数中的参数是:

flines- 从给定路径 () 读取文件String并返回该文件中的行列表 ( List<String>)

join- 连接给定的元素List<String>并返回一个String

collectInts- 解析给定String并返回在其中找到的整数列表String

sum- 添加元素List<Integers>并返回总和

问题:

  1. 我可以用第二种方法重载第一种方法吗?

  2. 除了功能之外,我还可以使用哪些其他现有功能接口?我认为没有,因为论点和结果的类型总是不同的。

4

1 回答 1

3

如果您想创建一个应用多个函数且对中间值不感兴趣的方法,您可以将其设为泛型方法。您问题中的代码很奇怪,因为它假设value可以同时是 aString和 a List<String>

但是与您的其他问题相比,情况有所不同。虽然 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))));
    }
}

假设您按照此答案中的描述修复了接口类型并创建了函数,您可以像这样使用它

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);
于 2015-10-23T12:38:19.077 回答