java8行为参数化/lambda实现示例
//定义Apple
public class Apple {
private String color;private int weight;
private String type;
public Apple(String color, String type, int weight) {this.color = color;
this.type = type;
this.weight = weight;
}
public String getColor() {
return this.color;
}
public void setColor(String color) {
this.color = color;
}
public int getWeight() {
return this.weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
public String getType() {
return this.type;
}
public void setType(String type) {
this.type = type;
}
@Override
public String toString() {
return "[" + this.color + "," + this.type + "," + this.weight + "]";
}
}
//定义函数式接口
public interface FilterPredicate<T> {
boolean filter(T t);
}
//定义函数式接口的一个实现
public class ApplePredicate implements FilterPredicate<Apple> {
@Override
public boolean filter(Apple apple) {
return apple.getColor().equalsIgnoreCase("red");
}
}
//
public class FHFilter {
public <T> List<T> filter(List<T> inventory, FilterPredicate<T> predicate) {
List<T> result = new ArrayList<T>();
for (T t : inventory) {
if (predicate.filter(t)) {
result.add(t);
}
}
return result;
}
}
//测试
public class Test {
public static void main(String[] args) {
FHFilter fhFilter = new FHFilter();
List<Apple> appleList = Arrays.asList(new Apple("red", "1", 110), new Apple("yellow", "2", 220), new Apple("red", "3", 330));
// 筛选System.out.println("+++++++++++++ 行为参数化 ++++++++++++++");
List<Apple> myApple = fhFilter.filter(appleList, new ApplePredicate());
System.out.println(myApple.toString());
System.out.println("+++++++++++++ lambda ++++++++++++++");
List<Apple> myApple2 = fhFilter.filter(appleList, (Apple apple) -> apple.getColor().equalsIgnoreCase("red"));
System.out.println(myApple2.toString());
}
}
-----------------------------------------------
运行结果如下:
+++++++++++++ 行为参数化 ++++++++++++++[[red,1,110], [red,3,330]]
+++++++++++++ lambda ++++++++++++++
[[red,1,110], [red,3,330]]