Java 8 Predicate with Examples

Java 8 Predicate with Examples

[toc]

A Functional Interface is an Interface which allows only one Abstract method within the Interface scope. There are some predefined functional interface in Java like Predicate, consumer, supplier etc. The return type of a Lambda function (introduced in JDK 1.8) is a also functional interface.The Functional Interface PREDICATE is defined in the java.util.function package. It improves manageability of code, helps in unit-testing them separately, and contain some methods like:
函數(shù)式接口是一種接口,在一個接口內(nèi)只允許一個抽象方法邀泉。Java中有許多預(yù)定義的函數(shù)式接口鸯隅,如:斷言predicate自阱,消費者consumer, 提供者supplier平窘,等等金拒。從jdk1.8引入募书,lambada函數(shù)的返回類型,也是一個函數(shù)式接口镶奉。函數(shù)式接口PREDICATE在 java.util.function 包中定義础淤。它增加了代碼的可維護性崭放,有助于分離代碼進行單元測試,并且包含了一些方法值骇,如:

1. isEqual(Object targetRef)

: Returns a predicate that tests if two arguments are equal according to Objects.equals(Object, Object).

static  Predicate isEqual(Object targetRef)
Returns a predicate that tests if two arguments are equal according to Objects.equals(Object, Object).
T : the type of arguments to the predicate Parameters:
targetRef : the object reference with which to compare for equality, which may be null
Returns: a predicate that tests if two arguments are equal according to Objects.equals(Object, Object)

2. and(Predicate other)

: Returns a composed predicate that represents a short-circuiting logical AND of this predicate and another.

default Predicate and(Predicate other)
Returns a composed predicate that represents a 
short-circuiting logical AND of this predicate and another.
Parameters:
other: a predicate that will be logically-ANDed with this predicate
Returns : a composed predicate that represents the short-circuiting 
logical AND of this predicate and the other predicate
Throws: NullPointerException - if other is null

3. negate()

: Returns a predicate that represents the logical negation of this predicate

default Predicate negate()
Returns:a predicate that represents the logical negation of this predicate

4.or(Predicate other)

: Returns a composed predicate that represents a short-circuiting logical OR of this predicate and another.

default Predicate or(Predicate other)
Parameters:
other : a predicate that will be logically-ORed with this predicate
Returns:a composed predicate that represents the short-circuiting logical OR of this predicate and the other predicate
Throws : NullPointerException - if other is null

5.test(T t)

: Evaluates this predicate on the given argument.boolean test(T t)

test(T t) 
Parameters: t - the input argument
Returns: true if the input argument matches the predicate, otherwise false

illustrate

Simple Predicate

// Java program to illustrate Simple Predicate

import java.util.function.Predicate;
public class PredicateInterfaceExample1 {
    public static void main(String[] args)
    {
        // Creating predicate
        Predicate<Integer> lesserthan = i -> (i < 18);

        // Calling Predicate method
        System.out.println(lesserthan.test(10));  
        //True
    }
}

Predicate Chaining

// Java program to illustrate Predicate Chaining

import java.util.function.Predicate;
public class PredicateInterfaceExample2 {
    public static void main(String[] args)
    {
        Predicate<Integer> greaterThanTen = (i) -> i > 10;

        // Creating predicate
        Predicate<Integer> lowerThanTwenty = (i) -> i < 20;
        boolean result = greaterThanTen.and(lowerThanTwenty).test(15);
        System.out.println(result);

        // Calling Predicate method
        boolean result2 = greaterThanTen.and(lowerThanTwenty).negate().test(15);
        System.out.println(result2);
        
        //output 
        //True
        //False
    }
}

passing Predicate into function

// Java program to illustrate passing Predicate into function

import java.util.function.Predicate;
class PredicateInterfaceExample3 {
    static void pred(int number, Predicate<Integer> predicate)
    {
        if (predicate.test(number)) {
            System.out.println("Number " + number);
        }
    }
    public static void main(String[] args)
    {
        pred(10, (i) -> i > 7);
        
        //output 
        //Number 10
    }
}

OR Predicate

// Java program to illustrate OR Predicate

import java.util.function.Predicate;
class PredicateInterfaceExample4 {
    public static Predicate<String> hasLengthOf10 = new Predicate<String>() {
        @Override
        public boolean test(String t)
        {
            return t.length() > 10;
        }
    };

    public static void predicate_or()
    {

        Predicate<String> containsLetterA = p -> p.contains("A");
        String containsA = "And";
        boolean outcome = hasLengthOf10.or(containsLetterA).test(containsA);
        System.out.println(outcome);
    }
    public static void main(String[] args)
    {
        predicate_or();
    }
    //output: True
}

AND Predicate

// Java program to illustrate AND Predicate

import java.util.function.Predicate;
import java.util.Objects;

class PredicateInterfaceExample5 {
    public static Predicate<String> hasLengthOf10 = new Predicate<String>() {
        @Override
        public boolean test(String t)
        {
            return t.length() > 10;
        }
    };

    public static void predicate_and()
    {
        Predicate<String> nonNullPredicate = Objects::nonNull;

        String nullString = null;

        boolean outcome = nonNullPredicate.and(hasLengthOf10).test(nullString);
        System.out.println(outcome);

        String lengthGTThan10 = "Welcome to the machine";
        boolean outcome2 = nonNullPredicate.and(hasLengthOf10).
        test(lengthGTThan10);
        System.out.println(outcome2);
    }
    public static void main(String[] args)
    {
        predicate_and();
    }
    //output
    //False
    //True
}

接口源碼

@FunctionalInterface
public interface Predicate<T> {
    /**
     * 具體過濾操作 需要被子類實現(xiàn).
     * 用來處理參數(shù)T是否滿足要求,可以理解為 條件A
     */
    boolean test(T t);
    /**
     * 調(diào)用當前Predicate的test方法之后再去調(diào)用other的test方法,相當于進行兩次判斷
     * 可理解為 條件A && 條件B
     */
    default Predicate<T> and(Predicate<? super T> other) {
        Objects.requireNonNull(other);
        return (t) -> test(t) && other.test(t);
    }
    /**
     * 對當前判斷進行"!"操作,即取非操作莹菱,可理解為 ! 條件A
     */
    default Predicate<T> negate() {
        return (t) -> !test(t);
    }
    /**
     * 對當前判斷進行"||"操作,即取或操作,可以理解為 條件A ||條件B
     */
    default Predicate<T> or(Predicate<? super T> other) {
        Objects.requireNonNull(other);
        return (t) -> test(t) || other.test(t);
    }

    /**
     * 對當前操作進行"="操作,即取等操作,可以理解為 A == B
     */
    static <T> Predicate<T> isEqual(Object targetRef) {
        return (null == targetRef)
                ? Objects::isNull
                : object -> targetRef.equals(object);
    }
}

原文:Java 8 Predicate with Examples - GeeksforGeeks

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末移国,一起剝皮案震驚了整個濱河市吱瘩,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌迹缀,老刑警劉巖使碾,帶你破解...
    沈念sama閱讀 216,496評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異祝懂,居然都是意外死亡票摇,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,407評論 3 392
  • 文/潘曉璐 我一進店門砚蓬,熙熙樓的掌柜王于貴愁眉苦臉地迎上來矢门,“玉大人,你說我怎么就攤上這事灰蛙∷钐蓿” “怎么了?”我有些...
    開封第一講書人閱讀 162,632評論 0 353
  • 文/不壞的土叔 我叫張陵摩梧,是天一觀的道長物延。 經(jīng)常有香客問我,道長仅父,這世上最難降的妖魔是什么叛薯? 我笑而不...
    開封第一講書人閱讀 58,180評論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮笙纤,結(jié)果婚禮上耗溜,老公的妹妹穿的比我還像新娘。我一直安慰自己省容,他們只是感情好强霎,可當我...
    茶點故事閱讀 67,198評論 6 388
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著蓉冈,像睡著了一般城舞。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上寞酿,一...
    開封第一講書人閱讀 51,165評論 1 299
  • 那天家夺,我揣著相機與錄音,去河邊找鬼伐弹。 笑死拉馋,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播煌茴,決...
    沈念sama閱讀 40,052評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼随闺,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了蔓腐?” 一聲冷哼從身側(cè)響起矩乐,我...
    開封第一講書人閱讀 38,910評論 0 274
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎回论,沒想到半個月后散罕,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,324評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡傀蓉,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,542評論 2 332
  • 正文 我和宋清朗相戀三年欧漱,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片葬燎。...
    茶點故事閱讀 39,711評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡误甚,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出谱净,到底是詐尸還是另有隱情窑邦,我是刑警寧澤,帶...
    沈念sama閱讀 35,424評論 5 343
  • 正文 年R本政府宣布岳遥,位于F島的核電站奕翔,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏浩蓉。R本人自食惡果不足惜派继,卻給世界環(huán)境...
    茶點故事閱讀 41,017評論 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望捻艳。 院中可真熱鬧驾窟,春花似錦、人聲如沸认轨。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,668評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽嘁字。三九已至恩急,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間纪蜒,已是汗流浹背衷恭。 一陣腳步聲響...
    開封第一講書人閱讀 32,823評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留纯续,地道東北人随珠。 一個月前我還...
    沈念sama閱讀 47,722評論 2 368
  • 正文 我出身青樓灭袁,卻偏偏與公主長得像,于是被迫代替她去往敵國和親窗看。 傳聞我的和親對象是個殘疾皇子茸歧,可洞房花燭夜當晚...
    茶點故事閱讀 44,611評論 2 353

推薦閱讀更多精彩內(nèi)容