Java8 method reference used as Function object to combine functions

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

    You can just save it into a variable:

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

    Or you can use a cast, but it's less readable, IMO:

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

提交回复
热议问题