天天看點

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]
    }