面向对象编程是对数据进行抽象,而函数式编程是对行为进行抽象。现实世界中,数据和行为并存
第二章 Lambda表达式
匿名内部类:
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.out.println("button clicked");
}
});
使用Lambdas,event的括号要不要都行。
button.addActionListener((event) -> System.out.println("button clicked"));
Lambda表达式其他变体:
Runnable noArguments = () -> System.out.println("Hello World");
Runnable multiStatement = () -> {
System.out.print("Hello");
System.out.println(" World");
};
ActionListener oneArgument = event -> System.out.println("button clicked");
BinaryOperator<Long> add = (x, y) -> x + y;
BinaryOperator<Long> addExplicit = (Long x, Long y) -> x + y;
这些都是接口的实现。
什么是函数接口?
函数接口是只有一个抽象方法的接口,用作Lambda表达式的类型。
java中重要的函数接口
接口 | 参数 | 返回类型 | 实例 |
---|---|---|---|
Predicate | T | boolean | 这张唱片发行了没? |
Consumer | T | void | 利用输入参数,println输出一个值 |
Function | T | R | 获得一个Car对象的名字 |
Supplier | None | T | 工厂方法 |
UnaryOperator | T | T | 逻辑非(!) |
BinaryOperator | (T,T) | T | 求两个乘数的乘积 |
如,类型推断
Predicate<Integer> atLeast5 = x -> x > 5;