简体   繁体   中英

Convert an for each loop with var inside to a Java Stream?

I have a function:

String fun(List<Function<String, String>> pro, String x){

     for(var p: pro){
         x = p.apply(x);
     }
     return x; 
}

How can I convert this function to functional style instead of imperative style?

Assuming what you want is to apply each function to your string, passing along the result of each function to the next, you can do this with reduce .

String fun(List<Function<String, String>> functions, String x) {
    return functions.stream()
                    .reduce(s -> s, Function::andThen)
                    .apply(x);
}

Using reduce with andThen creates a combined function that chains your list of functions together. We then apply the combined function to x .

Alternatively, @Naman in the comments suggests the formulation:

functions.stream()
         .reduce(Function::andThen)
         .orElse(Function.identity())
         .apply(x)

which I believe performs one fewer andThen operation (when the list of functions is nonempty), but is functionally the same as the first version.

( Function.identity() is an another way to write s -> s .)

I believe you are already aware about those compilation errors. You can't just define List<Function<>> without having a common understanding about those list of functions. Maybe you can get some inspiration from below code snippet.

String fun(List<Function<String, String>> listOfFunctions, String commonInputStr){
    for (Function<String, String> function : listOfFunctions) {
        String tempValStr = function.apply(commonInputStr);
        if (tempValStr != null){
            return tempValStr;
        }
    }

    return null;
}

Or if you want to find the first result value like below:

Optional<String> fun(List<Function<String, String>> listOfFunctions, String commonInputStr){

    return listOfFunctions.stream()
            .map(stringStringFunction -> stringStringFunction.apply(commonInputStr))
            .findFirst();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM