亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

傳遞一些 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 關注
  • 161 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號