目录
目录

Java函数式编程

  • 商业发展需要更多复杂的应用,大多数程序都跑在功能强大的多核CPU的机器上,带有高效运行时编译器的Java虚拟机的出现,能让程序员将更多的精力放在编写干净、易于维护的代码上,而不是思考如何将每一个CPU时钟周期、每字节内存物尽其用。
  • 多核CPU的兴起成为了不容回避的事实。涉及锁的编程算法不但容易出错,而且耗费时间。人们开发了java.util.concurrent包和很多第三方类库,试图将并发抽象化,帮助程序员写出在多核CPU上运行良好的程序。很可惜,到目前为止,这方面的成果还远远不够!
  • 面向对象编程是对数据进行抽象,而函数式编程是对行为进行抽象。现实世界中,数据和行为并存,程序也是如此。

  • Swing的事件监听器

1
2
3
4
5
6
7
8
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.out.print("button clicked");
}
});
  • 转为Lambda表达式
1
button.addActionListener( event -> System.out.print("button clicked"));
  • 各种形式的Lambda表达式
1
2
3
4
5
6
7
8
9
10
11
Runnable noArguments = () -> System.out.print("button clicked")
Runnable multiStatement = () -> {
System.out.print("Hello");
System.out.print("world");
}
button.addActionListener( event -> System.out.print("button clicked"));
BinaryOperator<Long> add = (x, y) -> x + y;
BinaryOperator<Long> addExplicit = (Long x, Long y) -> x + y;