05 函数式编程接口Predicate

2020-04-03  本文已影响0人  张力的程序园

本节讲述函数式编程接口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);
    }
}
        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接口的基本使用。

上一篇 下一篇

猜你喜欢

热点阅读