Predicate(谓词)
谓词(predicate)
在数学上常常用来代表一个类似函数的东西,它接受一个参数值,并返回true或false。
理解
行为参数化就是可以帮助你处理频繁变更的需求的一种软件开发模式。一言以蔽之,它意味
着拿出一个代码块,把它准备好却不去执行它。这个代码块以后可以被你程序的其他部分调用,
这意味着你可以推迟这块代码的执行。例如,你可以将代码块作为参数传递给另一个方法,稍后
再去执行它。这样,这个方法的行为就基于那块代码被参数化了。
基本使用
public class PredicateDemo {
public static void main(String[] args) {
List<Apple> apples = Arrays.asList(new Apple(80,"green"), new Apple(120,"green"),new Apple(32,"red"));
List<Apple> result = filter(apples,apple -> apple.weight > 50);
System.out.println(result);
}
static List<Apple> filter(List<Apple> apples, Predicate<Apple> p) {
return apples.stream().filter(p).collect(Collectors.toList());
}
}
class Apple {
int weight;
String color;
Apple(int weight, String color) {
this.color = color;
this.weight = weight;
}
@Override
public String toString() {
return "Apple{" +
"weight=" + weight +
", color='" + color + '\'' +
'}';
}
}

浙公网安备 33010602011771号