传递几个lambda作为方法的参数

时间:2019-11-04 09:39:09

标签: java lambda compose

我想将一些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);
    ...

1 个答案:

答案 0 :(得分:1)

我认为您必须编写返回类型取决于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);
    }
 }

然后可以使用标准方法Functioncompose组合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

或写自己。