谓词及功能复合,就是在通过组合已有的谓词或功能,形成更加复杂的谓词或功能。
谓词复合
谓词(Predicate
)接口包含三个方法:negate
、and
和or
,通过这三个方法,我们可以在已有谓词的基础上,组合形成更加复杂的谓词。negate
代表非,and
代表和,or
代表或。
举个例子,我们有一个苹果(Apple
)类,包含颜色(color
)和重量(weight
)两个属性。
class Apple {
public Apple(String color, double weight) {
this.color = color;
this.weight = weight;
}
private String color;
private double weight;
@Override
public String toString() {
return "color:" + color + "---------" + "weight:" + weight;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
}
然后我们创建一个苹果的列表,存储几条测试数据。
List<Apple> appleList = new ArrayList<>();
appleList.add(new Apple("red", 2));
appleList.add(new Apple("red", 6));
appleList.add(new Apple("green", 2));
appleList.add(new Apple("green", 6));
negate测试
我们创建一个查找红色苹果的谓词
Predicate<Apple> redApple = apple -> "red".equals(apple.getColor());
然后创建一个查找不是红色苹果的谓词
List<Apple> notRedAppleList = appleList.stream().filter(notRedApple).collect(Collectors.toList());
for (Apple apple : notRedAppleList) {
System.out.println(apple);
}
and测试
我们首先创建一个查找重量大于5的谓词
Predicate<Apple> weightThan5Apple = apple -> apple.getWeight() > 5;
然后组合红苹果及重量大于5的两个谓词
Predicate<Apple> redAndWeightThan5Apple = redApple.and(weightThan5Apple);
测试
List<Apple> redAndWeightThan5AppleList = appleList.stream().filter(redAndWeightThan5Apple).collect(Collectors.toList());
for (Apple apple : redAndWeightThan5AppleList) {
System.out.println(apple);
}
or测试
还是利用刚才的谓词,这次我们测试重量大于5或者颜色是红色的苹果
Predicate<Apple> redOrWeightThan5Apple = redApple.or(weightThan5Apple);
测试
List<Apple> redOrWeightThan5AppleList = appleList.stream().filter(redOrWeightThan5Apple).collect(Collectors.toList());
for (Apple apple : redOrWeightThan5AppleList) {
System.out.println(apple);
}
函数复合
函数复合跟谓词复合类似,函数复合提供了两个接口方法:andThen
和compose
,通过字面含义我们可以知道andThen
代表先执行第一个函数,然后在执行第二个函数,compose
与之相反,先执行第二个函数,在执行第一个函数。
Function<Integer, Integer> funcPlus = x -> x + 1;
Function<Integer, Integer> funcMul = y -> y * 2;
Function<Integer, Integer> funcAndThen = funcPlus.andThen(funcMul);
Function<Integer, Integer> funcCompose = funcPlus.compose(funcMul);
System.out.println("andThen:" + funcAndThen.apply(1));
System.out.println("compose:" + funcCompose.apply(1));
通过测试,我们发现andThen
先执行了第一个函数,也就是1+1=2
,然后执行2*2=4
,所以最终结果就是4
。compose
限制性1*2=2
,然后执行1+2=3
,所以结果是3
。
评论 (0)