从Java 8中的Method返回Lambda?

Phi*_*rdi 27 java lambda java-8

我刚刚开始使用Java 8,我想知道是否有办法编写一个返回的方法Function

现在我的方法如下:

Function<Integer, String> getMyFunction() {
  return new Function<Integer, String>() {
    @Override public String apply(Integer integer) {
      return "Hello, world!"
    }
  } 
}
Run Code Online (Sandbox Code Playgroud)

有没有办法在Java 8中更简洁地编写?我希望这会起作用,但它不会:

Function<Integer, String> getMyFunction() {
  return (it) -> { return "Hello, world: " + it } 
}
Run Code Online (Sandbox Code Playgroud)

mko*_*bit 34

摆脱函数定义中的return语句:

Function<Integer, String> getMyFunction() {
    return (it) -> "Hello, world: " + it;
}
Run Code Online (Sandbox Code Playgroud)


ass*_*ias 17

你缺少半冒号:

return (it) -> { return "Hello, world: " + it; };
Run Code Online (Sandbox Code Playgroud)

虽然如上所述它可以缩短为:

return it -> "Hello, world: " + it;
Run Code Online (Sandbox Code Playgroud)


Ous*_*ami 5

你可以简单地这样写:

Function<Integer, String> function = n -> "Hello, world " + n;
Run Code Online (Sandbox Code Playgroud)


Mag*_*lex 5

我想指出,IntFunction在这种情况下,使用内置功能可能更合适:

IntFunction<String> getMyFunction() {
    return it -> "Hello, world: " + it;
}
Run Code Online (Sandbox Code Playgroud)

IntFunction功能接口标准API的一部分,该接口定义了许多具有接口的商品,这些接口主要与Java原语相关。