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<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]]


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值