美文网首页
05 函数式编程接口Predicate

05 函数式编程接口Predicate

作者: 张力的程序园 | 来源:发表于2020-04-03 16:20 被阅读0次

本节讲述函数式编程接口Predicate的使用。

  • Predicate< T >: 条件测试器,接收一个 T 类型的对象,返回布尔值,通常用于传递条件函数; 单参数布尔值的条件性接口。提供了 test (条件测试) , and-or- negate(与或非) 方法。其中, compose, andThen, and, or, negate 用来组合函数接口而得到更强大的函数接口。
    Predicate的源代码:
package java.util.function;

import java.util.Objects;
@FunctionalInterface
public interface Predicate<T> {
    boolean test(T t);

    default Predicate<T> and(Predicate<? super T> other) {
        Objects.requireNonNull(other);
        return (t) -> test(t) && other.test(t);
    }

    default Predicate<T> negate() {
        return (t) -> !test(t);
    }

    default Predicate<T> or(Predicate<? super T> other) {
        Objects.requireNonNull(other);
        return (t) -> test(t) || other.test(t);
    }

    static <T> Predicate<T> isEqual(Object targetRef) {
        return (null == targetRef)
                ? Objects::isNull
                : object -> targetRef.equals(object);
    }
}
  • 测试test方法,返回小于7的整数
        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
        List<Integer> result = list.stream().filter(integer -> integer<7).collect(Collectors.toList());
        result.forEach(System.out::println);

以上就是Predicate接口的基本使用。

相关文章

网友评论

      本文标题:05 函数式编程接口Predicate

      本文链接:https://www.haomeiwen.com/subject/jyghphtx.html