为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PIPIONE 2024-01-28 17:06:26
我想将一些 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 回答

?
千巷猫影

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

或者自己写。


查看完整回答
反对 回复 2024-01-28
  • 1 回答
  • 0 关注
  • 20 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信