Java8中引入的“新功能”,用起来确实很方便,它的关键是
**
- 允许将“方法”作为参数来进行传递
- “方法”的定义分成两部分
**
紧抓这两个点,就能很好的使用Lambda表达式了
演变
在程序编写过程中,我们总会 多态 这种情况,比如:
public class LearnLambdaNormal {// 动物interface Animal {void eat(String food);}public static void main(String[] args) {// 猫Animal cat = new Animal() {public void eat(String food) {System.out.println(String.format("猫要吃:%s", food));}};// 狗Animal dog = new Animal() {public void eat(String food) {System.out.println(String.format("狗要吃: %s", food));}};// 人class Person {public void feed(Animal animal, String food) {animal.eat(food);}}Person person = new Person();// 喂小动物person.feed(cat, "鱼干");person.feed(dog, "骨头");}}
在 34、35 行,我们最终的目的,其实是想要执行一个方法而已,但我们却额外的定义了一个接口 Animal 和两个类 cat 、 dog ,而 Animal 接口就一个方法,只是方法的内部实现不一样而已,那能不能提供一种机制,让我们
传递要执行的方法 呢?
这时候就需要用到 Lambda表达式了,如果用 Lambda表达式改写上面的代码,就简化成了
public class LearnLambdaExpress {public static void main(String[] args) {// 人class Person {public void feed(Consumer<String> animal, String food) {animal.accept(food);}}Person person = new Person();// 喂小动物person.feed(x -> System.out.println(String.format("猫吃: %s", x)), "鱼干");person.feed(x -> System.out.println(String.format("够吃: %s", x)), "骨头");}}
在第 14 、 15 行,直接实现了我们的目的,执行不同的方法,是不是简单很多
