天天看点

java8 Predicate

前言: 啊吖吖~,我又来分享java8新特性系列函数了,最近有在努力学习,认真分享知识,也希望认真阅读的你发光脑门不亮,点赞~笔芯

Predicate也是java8新特性里面的函数式接口,当我们使用Java Stream API中的filter方法时尤为重要,因为filter的参数是Predicate类型,下面让我们用简单的栗子,看下各个方法的使用。

@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);
    }
}
           

1.test(T t)方法

首先定义predicate变量,Lambda表达式是要执行的逻辑代码。当执行predicate.test("java")时,"java"作为参数,执行str.startsWith("j") ,返回执行结果boolean值。

public static void main(String[] args) {
        Predicate<String> predicate= str -> str.startsWith("j");
        boolean test1 = predicate.test("java");
        System.out.println(test1);//true
        boolean test2 = predicate.test("c++");
        System.out.println(test2);//false
    }
           

2. and(Predicate<? super T> other)方法

总结:A.and(B)方法,相当于A&&B,同时满足A,B两个表达式

3.negate()方法

总结:A.negate()方法,相当于!A,对A条件取反

4.or(Predicate<? super T> other)方法

总结:A.or(B)方法,相当于A||B,满足A表达式或者满足B表达式

5.isEqual(Object targetRef)静态方法

返回集合中是否有和传入参数相同的值,也可以是对象(需要重写equal()方法和hasCode()方法)

如果觉得有收获,请为互联网美少女刘可爱点个赞吧。

public static void main(String[] args) {
        ArrayList<String> list = Lists.newArrayList("java", "python3", "javascrip", "golang", "c++", "jquery");
        Predicate<String> predicate= str -> str.startsWith("j");
        Predicate<String> predicate1 = s -> s.length() > 5;
        //过滤以j开头的字符串
        List<String> collect1 = list.stream().filter(predicate).collect(Collectors.toList());
        System.out.println(collect1);//[java, javascrip, jquery]

        //过滤不是以j开头的字符串
        List<String> collect2 = list.stream().filter(predicate.negate()).collect(Collectors.toList());
        System.out.println(collect2);//[python3, golang, c++]

        //过滤满足字符串以j开头并且长度大于5
        List<String> collect3 = list.stream().filter(predicate.and(predicate1)).collect(Collectors.toList());
        System.out.println(collect3);//[javascrip, jquery]

        //过滤以j开头或者长度大于5
        List<String> collect4 = list.stream().filter(predicate.or(predicate1)).collect(Collectors.toList());
        System.out.println(collect4);//[java, python3, javascrip, golang, jquery]

        //过滤集合中是"jquery"的字符串
        List<String> java = list.stream().filter(Predicate.isEqual("jquery")).collect(Collectors.toList());
        System.out.println(java);//[jquery]
    }