1 Predicate
@FunctionalInterface
public interface Predicate<T> {
/**
* Evaluates this predicate on the given argument.
*
* @param t the input argument
* @return {@code true} if the input argument matches the predicate,
* otherwise {@code false}
*/
boolean test(T t);
....
}
- 字面意思就是断言,接受一个泛型T,返回一个boolean值,可用于对T进行断言,简单的用法如下
/**
* @Description Predicate 入门
* @Author wyaoyao
* @Date 2020/8/24 8:52 下午
* @Param
* @Return
* @Exception
*/
@Test
public void testBasic(){
// 判断是否大于0
Predicate<Integer> predicate = (a) -> a>0;
boolean reslut = predicate.test(1);
Assert.assertThat(reslut,equalTo(true));
}
- 上节我们自己定义的filter其实就完全可以用Predicate代替
public List<Apple> filterApple(List<Apple> target, Predicate<Apple> predicate) {
List<Apple> result = new ArrayList<>();
for (Apple apple : target) {
if(predicate.test(apple)){
result.add(apple);
}
}
return result;
}
@Test
public void testFilterApple() {
List<Apple> apples = Arrays.asList(new Apple(ColorConstants.GREEN, 150), new Apple(ColorConstants.RED, 120));
List<Apple> result = filterApple(apples, apple -> apple.getColor().equals(ColorConstants.RED));
log.info("filter result {}", apples);
}
2 LongPredicate
@FunctionalInterface
public interface LongPredicate {
/**
* Evaluates this predicate on the given argument.
*
* @param value the input argument
* @return {@code true} if the input argument matches the predicate,
* otherwise {@code false}
*/
boolean test(long value);
}
和Predicate的区别就是明确了入参是long类型的,相似的还有DoublePredicate
@Test
public void testBasic() {
LongPredicate predicate = (a) -> a > 0;
boolean reslut = predicate.test(0L);
Assert.assertThat(reslut, equalTo(false));
}
3 BiPredicate
@FunctionalInterface
public interface BiPredicate<T, U> {
/**
* Evaluates this predicate on the given arguments.
*
* @param t the first input argument
* @param u the second input argument
* @return {@code true} if the input arguments match the predicate,
* otherwise {@code false}
*/
boolean test(T t, U u);
- 这个也没什么,就是接收两个参数而已
@Test
public void testBiPredicate() {
BiPredicate<String,Long> predicate = (a,b)->a.equals("a") && b>0;
boolean reslut = predicate.test("a",0L);
Assert.assertThat(reslut, equalTo(false));
}
List<Apple> filterAppleByBiPredicate(List<Apple> target, BiPredicate<String, Long> biPredicate) {
List<Apple> result = new ArrayList<>();
for (Apple apple : target) {
if (biPredicate.test(apple.getColor(), apple.getWeight())) {
result.add(apple);
}
}
return result;
}
@Test
public void testFilterAppleByBiPredicate() {
List<Apple> apples = Arrays.asList(new Apple(ColorConstants.GREEN, 150), new Apple(ColorConstants.RED, 120));
List<Apple> result = filterAppleByBiPredicate(apples, (color, weight) -> color.equals(ColorConstants.RED) && weight >= 100);
log.info("filter result {}", result);
}