昨天我偶然发现了一些我既不懂也不能找到解释的东西:
请考虑以下操作:
Stream.of(1, 2, 3).map(i -> i * 2).forEach(System.out::println);
//This one won't compile
Stream.of(1, 2, 3).map(i -> { i * 2; }).forEach(System.out::println);
Run Code Online (Sandbox Code Playgroud)
似乎第二个可以延伸到
Stream.of(1, 2, 3).map(i -> { return i * 2;}).forEach(System.out::println);
Run Code Online (Sandbox Code Playgroud)
它会编译好.我想出了这个,因为我已经习惯了第一个版本,但我的IDE(Netbeans)总是引用最后一个版本.
所以我的问题是:这两种实现的区别/优势是什么?为什么带有{}块的那个需要返回值?需要该值的位置(编译代码除外)?
更新:
关于在Java 8 lambda语法中何时使用大括号?,这个不能仅仅因为关于lambda表达式语法
Stream.of(1, 2, 3).forEach(i -> { System.out.println(i); });
Run Code Online (Sandbox Code Playgroud)
编译好,所以必须(从我的下面)关于实现map().
干杯,本
我目前正在开始使用javafx 8,并在一个简单的解决方案中提出了以下问题:
我有不同的控件(Button),它们会出现
Pane)Pane)
Button one = new Button("1");
Button two = new Button("2");
Button three = new Button("3");
VBox vbox = new VBox();
vbox.getChildren().addAll(one, two, three);
HBox hbox = new HBox();
hbox.getChildren().addAll(two, three); //To clarify my problem i leave one node in vbox
Run Code Online (Sandbox Code Playgroud)
现在似乎发生了最后一个.addAll(),删除了另一个框中的引用.
BorderPane root = new BorderPane();
root.setCenter(vbox);
root.setBottom(hbox);
Run Code Online (Sandbox Code Playgroud)
输出:

我尝试(测试)只是重复使用一个按钮,但是:
root.setCenter(one);
root.setBottom(one);
Run Code Online (Sandbox Code Playgroud)
结果是
java.lang.reflect.InvocationTargetException
...
Caused by: java.lang.RuntimeException: Exception in Application …Run Code Online (Sandbox Code Playgroud)