天天看點

JDK8 之 Predicate

作用:Predicate函數式接口的作用就是提供一個test方法,接受一個參數傳回一個布爾類型。
@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);
}
           

一、具體應用

package com.javatec.predicate;

import org.junit.Test;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * Predicate
 *
 * @author 王亞楠
 * @time 2018年03月21日 10:23
 **/
public class PredicateTest {

    @Test
    public void predicate() {
        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
        PredicateTest predicateTest = new PredicateTest();
        //輸出大于5的數字
        List<Integer> result = predicateTest.conditionFilter(list, s -> s > 5);
        result.forEach(System.out::println);
    }
        
    //高度抽象的方法定義,複用性高
    private List<Integer> conditionFilter(List<Integer> list, Predicate<Integer> predicate) {
        return list.stream().filter(predicate).collect(Collectors.toList());
    }
}
           

先解釋一下:list.stream().filter(predicate).collect(Collectors.toList());

  • stream 将 list 當做一個流來處理
  • filter 根據 predicate 的條件進行過濾,具體實作裡會調用 predicate 的 test() 方法
  • collect 将通過 filter 的結果合并成一個 List(Collectors.toList)

輸出:

6
7
8
9
10
           

可以看出,我們隻需要定義一個conditionFilter方法就可以通過函數式程式設計 指定任意 的 predicate, 上面我們實作的predicate是 s -> s > 5;

我們也可以進行下面的定義

//輸出大于等于5的數字
        result = predicateTest.conditionFilter(list, integer -> integer >= 5);
        result.forEach(System.out::println);
        System.out.println("-------");
           

可以卡出我們隻需要定義一個conditonFilter就可以完成各種自定義的條件過濾;

二、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);

    /**
     * Returns a composed predicate that represents a short-circuiting logical
     * AND of this predicate and another.  When evaluating the composed
     * predicate, if this predicate is {@code false}, then the {@code other}
     * predicate is not evaluated.
     *
     * <p>Any exceptions thrown during evaluation of either predicate are relayed
     * to the caller; if evaluation of this predicate throws an exception, the
     * {@code other} predicate will not be evaluated.
     *
     * @param other a predicate that will be logically-ANDed with this
     *              predicate
     * @return a composed predicate that represents the short-circuiting logical
     * AND of this predicate and the {@code other} predicate
     * @throws NullPointerException if other is null
     */
    default Predicate<T> and(Predicate<? super T> other) {
        Objects.requireNonNull(other);
        return (t) -> test(t) && other.test(t);
    }

    /**
     * Returns a predicate that represents the logical negation of this
     * predicate.
     *
     * @return a predicate that represents the logical negation of this
     * predicate
     */
    default Predicate<T> negate() {
        return (t) -> !test(t);
    }

    /**
     * Returns a composed predicate that represents a short-circuiting logical
     * OR of this predicate and another.  When evaluating the composed
     * predicate, if this predicate is {@code true}, then the {@code other}
     * predicate is not evaluated.
     *
     * <p>Any exceptions thrown during evaluation of either predicate are relayed
     * to the caller; if evaluation of this predicate throws an exception, the
     * {@code other} predicate will not be evaluated.
     *
     * @param other a predicate that will be logically-ORed with this
     *              predicate
     * @return a composed predicate that represents the short-circuiting logical
     * OR of this predicate and the {@code other} predicate
     * @throws NullPointerException if other is null
     */
    default Predicate<T> or(Predicate<? super T> other) {
        Objects.requireNonNull(other);
        return (t) -> test(t) || other.test(t);
    }

    /**
     * Returns a predicate that tests if two arguments are equal according
     * to {@link Objects#equals(Object, Object)}.
     *
     * @param <T> the type of arguments to the predicate
     * @param targetRef the object reference with which to compare for equality,
     *               which may be {@code null}
     * @return a predicate that tests if two arguments are equal according
     * to {@link Objects#equals(Object, Object)}
     */
    static <T> Predicate<T> isEqual(Object targetRef) {
        return (null == targetRef)
                ? Objects::isNull
                : object -> targetRef.equals(object);
    }
}

           

我們需要關注下面兩點:

  • 從and , or 和 negate() 方法的傳回值來看,隻是内部傳回了一個Predicate。
  • isEqual() 是一個靜态方法,參數和之前的方法不同,接收一個 Object ,最後調用的還是對象的 Equals方法。

參考部落格位址:

部落格:Java8-6-Predicate接口詳解

部落客:尹昊

我的個人部落格,有空來坐坐