使用谓词(Predicate)传递方法为参数,且通过Lambda表达式时间最简洁写法

//定义一个apple类
public class Apple {

public Apple(int welght, String color) {
this.color = color;
this.welght = welght;
}

private int welght;
private String color;

public int getWelght() {
return welght;
}

public void setWelght(int welght) {
this.welght = welght;
}

public String getColor() {
return color;
}

public void setColor(String color) {
this.color = color;
}
}

class TestDemo {
/**
* @param inventory 库存
* @return 颜色为绿色的所有苹果
*/
public static List<Apple> filterGreenApples(List<Apple> inventory) {
List<Apple> result = new ArrayList<>();
for (Apple apple : inventory) {
if ("green".equals(apple.getColor())) {
result.add(apple);
}
}
return result;
}

//重量大于150的所有苹果
public static List<Apple> filterHeavyApples(List<Apple> inventory) {
List<Apple> result = new ArrayList<>();
for (Apple apple : inventory) {
if (apple.getWelght() > 150) {
result.add(apple);
}
}
return result;
}

  //以上查找苹果的2个方法 只有判断苹果条件(颜色、重量)这句代码不同,其他代码一致
//下面将这些条件作为参数传递给方法,统一代码书写方式

public static boolean isGreenApple(Apple apple) {
return "green".equals(apple.getColor());
}

public static boolean isHeavyApple(Apple apple) {
return apple.getWelght() > 150;
}

public interface Predicate<T> {
boolean test(T t);
}

static List<Apple> filterApples(List<Apple> inventory, Predicate<Apple> p) {
List<Apple> result = new ArrayList<>();
for (Apple apple : inventory) {
//apple是否符合条件
if (p.test(apple)) {
result.add(apple);
}
}
return result;
}

static void main(String[] args) {
List<Apple> appleList = new ArrayList<>();
//Apple::isGreenApple 接受参数Apple并返回一个boolean
//filterApples(appleList, Apple::isGreenApple);
//最简洁filterApples(List<Apple> inventory,Predicate<Apple> p)的写法
filterApples(appleList, (Apple a) -> "green".equals(a.getColor()));
filterApples(appleList, (Apple a) -> a.getWelght() > 150 || "brown".equals(a.getColor()));
}
posted @ 2017-02-22 10:30  jims u  阅读(404)  评论(0)    收藏  举报