本文来自原创,如果出现错误 请留言指出
1.1. 需求
有一堆苹果,查找出所有红色的苹果;
1.2. 思路
实体类:苹果(成员变量 颜色)
接口:判断苹果的颜色是不是红色的
实现类:实现这个接口
实体类代码,只包含了一个成员变量:颜色
提供了get set 方法;
提供了无参构造 和 带有参数的构造,方便对象的创建
1 package com.aiiju.demo.pojo; 2 3 public class Apple { 4 // 只有一个变量 颜色,提供构造方法和toString方法 5 private String color; 6 public Apple() { 7 super(); 8 } 9 public Apple(String color) { 10 super(); 11 this.color = color; 12 } 13 public String getColor() { 14 return color; 15 } 16 public void setColor(String color) { 17 this.color = color; 18 } 19 @Override 20 public String toString() { 21 return "Apple [color=" + color + "]"; 22 } 23 }
接口代码;
只包含一个方法:判断苹果的颜色
1 package com.aiiju.demo; 2 import com.aiiju.demo.pojo.Apple; 3 4 @FunctionalInterface 5 public interface AppleFilter { 6 public boolean filterApple(Apple apple); 7 }
实现方案一:
通过实现类
package com.aiiju.demo; import com.aiiju.demo.pojo.Apple; public class AppleFilterImpl implements AppleFilter { @Override public boolean filterApple(Apple apple) { return "red".equals(apple.getColor()); } }
1.3. 测试类代码
1 package com.aiiju.demo; 2 import com.aiiju.demo.pojo.Apple; 3 4 public class AppleFilterImpl implements AppleFilter { 5 6 @Override 7 public boolean filterApple(Apple apple) { 8 return "red".equals(apple.getColor()); 9 } 10 }
代码分析
public List<Apple> makeApple()
这个方法是为了,生产多个苹果,因为会有很多地方需要这个方法;
下面这段代码,是重点;包含两个参数: 苹果的list。一个是接口;
1 public List<Apple> filterRedApple(List<Apple> apples, AppleFilter filter){ 2 List<Apple> result = new ArrayList<>(); 3 for (Apple apple : apples) { 4 if(filter.filterApple(apple)){ 5 result.add(apple); 6 } 7 } 8 return result; 9 }
这个接口。可以给的值 有三种
1, 一个实现类
2, 匿名内部类
3, Lambda 表达式
1.3.1. 使用实现类
实现类的方法简单:只需要要new 一个 实现类即可
@Test public void test1() throws Exception { List<Apple> apples = this.makeApple(); AppleFilter filter = new AppleFilterImpl(); List<Apple> filterRedApple = this.filterRedApple(apples, filter); System.out.println(filterRedApple); }
1.3.1. 使用匿名内部类
实现类的方法简单:
1 @Test 2 public void test2() throws Exception { 3 List<Apple> apples = this.makeApple(); 4 5 List<Apple> filterRedApple = this.filterRedApple(apples, new AppleFilter() { 6 7 @Override 8 public boolean filterApple(Apple apple) { 9 return "red".equals(apple.getColor()); 10 } 11 }); 12 System.out.println(filterRedApple); 13 }
你们内部类相当于一个实现类;
把匿名内部类进行简化
1.3.2. Lambda 表达式的写法
改成 lambda 写法;
1 @Test 2 public void test3() throws Exception { 3 List<Apple> apples = this.makeApple(); 4 5 List<Apple> filterRedApple = this.filterRedApple(apples, (Apple apple) -> { 6 return "red".equals(apple.getColor()); 7 }); 8 System.out.println(filterRedApple); 9 }
匿名内部类和 lambda 的写法进行比较
lambda 表达式可以进行简化,下面是简化的写法
还可以进行进一步的简化
最终简化的后的代码:
1 @Test 2 public void test5() throws Exception { 3 List<Apple> apples = this.makeApple(); 4 5 List<Apple> filterRedApple = this.filterRedApple(apples, apple -> "red".equals(apple.getColor()) ); 6 System.out.println(filterRedApple); 7 }
源码下载地址:https://files.cnblogs.com/files/tianming666/LambdaProject.rar
以上仅仅是我个人的理解;希望大家相互讨论共同进步