Java8 method reference used as Function object to combine functions

前端 未结 7 1583
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-14 15:02

Is there a way in Java8 to use a method reference as a Function object to use its methods, something like:

Stream.of(\"ciao\", \"hola\", \"hello         


        
相关标签:
7条回答
  • 2020-12-14 15:51

    We can use reduce function to combine multiple functions into one.

    public static void main(String[] args) {
        List<Function<String, String>> normalizers = Arrays.asList(
        str -> {
            System.out.println(str);
            return str;
        }, 
        String::toLowerCase,
        str -> {
            System.out.println(str);
            return str;
        },
        String::trim,
        str -> {
            System.out.println(str);
            return str;
        });
    
        String input = " Hello World ";
        normalizers.stream()
                   .reduce(Function.identity(), (a, b) -> a.andThen(b))
                   .apply(input);
    }
    

    Output:

     Hello World 
     hello world 
    hello world
    
    0 讨论(0)
提交回复
热议问题