java8行为参数化/lambda实现示例

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 {
boolean filter(T t);
}

//定义函数式接口的一个实现

public class ApplePredicate implements FilterPredicate {

@Override
public boolean filter(Apple apple) {
return apple.getColor().equalsIgnoreCase("red");
}

}

//

public class FHFilter {
public List filter(List inventory, FilterPredicate predicate) {
List result = new ArrayList();
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 appleList = Arrays.asList(new Apple("red", "1", 110), new Apple("yellow", "2", 220), new Apple("red", "3", 330));

// 筛选
System.out.println("+++++++++++++ 行为参数化 ++++++++++++++");
List myApple = fhFilter.filter(appleList, new ApplePredicate());
System.out.println(myApple.toString());
System.out.println("+++++++++++++ lambda ++++++++++++++");
List 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]]


你可能感兴趣的:(java)