传递一些 lambda 作为方法的参数

我想将一些 lambda 方法作为参数传递给该方法。不是一个 lambda,而是几个 lambda。怎么做?


flines = arg -> arg.startsWith("WAW");


String fname = System.getProperty("user.home") + "/LamComFile.txt"; 


InputConverter<String> fileConv = new InputConverter<>(fname);


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);

    ...


PIPIONE
浏览 29回答 1
1回答

千巷猫影

我认为你必须编写返回类型取决于Function参数的方法:class InputConverter<T> {&nbsp; &nbsp;private final T value;&nbsp; &nbsp; public InputConverter(T value) {&nbsp; &nbsp; &nbsp; &nbsp; this.value = value;&nbsp; &nbsp; }&nbsp; &nbsp; public <R> R convertBy(Function<T, R> function){&nbsp; &nbsp; &nbsp; &nbsp; return function.apply(value);&nbsp; &nbsp; }&nbsp;}然后您可以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(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; valueToListFunction&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .andThen(firstValueFunction));您也可以使用其他标准FunctionalInterfaces,例如UnaryOperator:UnaryOperator<String> firstChangeFunction = arg -> arg.concat(" + first");UnaryOperator<String> secondChangeFunction = arg -> arg.concat(" + second");String firstValue = inputConverter.convertBy(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; valueToListFunction&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .andThen(firstValueFunction)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .andThen(secondChangeFunction)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .compose(firstChangeFunction)); // sout: fname_value + first + second或者自己写。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java