Java8 method reference used as Function object to combine functions

前端 未结 7 1601
佛祖请我去吃肉
佛祖请我去吃肉 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:41

    You should be able to achieve what you want inline by using casts:

    Stream.of("ciao", "hola", "hello")
          .map(((Function) String::length).andThen(n -> n * 2))
    

    There are only 'type hints' for the compiler, so they don't actually 'cast' the object and don't have the overhead of an actual cast.


    Alternatively, you can use a local variable for readability:

    Function fun = String::length
    
    Stream.of("ciao", "hola", "hello")
          .map(fun.andThen(n -> n * 2));
    

    A third way that may be more concise is with a utility method:

    public static  Function chain(Function fun1, Function fun2)
    {
        return fun1.andThen(fun2);
    }
    
    Stream.of("ciao", "hola", "hello")
          .map(chain(String::length, n -> n * 2));
    

    Please note that this is not tested, thus I don't know if type inference works correctly in this case.

提交回复
热议问题