當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java Java.util.function.IntPredicate用法及代碼示例


IntPredicate接口被引入JDK 8。該接口封裝在java.util.function包。它對整數值進行操作並根據條件返回謂詞值。它是一個函數接口因此可以用於拉姆達表達式還。

public interface IntPredicate

方法:

  1. test():此函數對 int 值進行條件檢查,並返回一個表示結果的布爾值。
boolean test(int value)

2.and():此函數對當前對象和作為參數接收的對象進行 AND 運算,並返回新形成的謂詞。該方法有一個默認實現。

default IntPredicate and(IntPredicate other)

3. negate():該函數返回當前謂詞的逆,即反轉測試條件。該方法有一個默認實現。

default IntPredicate negate()

4. or():該函數對當前對象和作為參數接收的對象進行 OR 運算,並返回新形成的謂詞。該方法有一個默認實現。

default IntPredicate or(IntPredicate other)

例子:

Java


// Java example to demonstrate IntPredicate interface
import java.util.function.IntPredicate;
public class IntPredicateDemo {
    public static void main(String[] args)
    {
        // Predicate to check a value is less than 544331
        IntPredicate intPredicate = (x) ->
        {
            if (x <= 544331)
                return true;
            return false;
        };
        System.out.println("544331 is less than 544331 "
                           + intPredicate.test(544331));
        // Predicate to check a value is equal to 544331
        IntPredicate predicate = (x) ->
        {
            if (x == 544331)
                return true;
            return false;
        };
        System.out.println("544331 is equal to 544331 "
                           + predicate.test(544331));
        // ORing the two predicates
        IntPredicate intPredicate1 = intPredicate.or(predicate);
        System.out.println("544331 is less than equal to 544331 "
                           + intPredicate1.test(544331));
        // ANDing the two predicates
        intPredicate1 = intPredicate.and(predicate);
        System.out.println("544331 is equal to 544331 "
                           + intPredicate1.test(544331));
        // Negating the predicate
        intPredicate1 = intPredicate.negate();
        System.out.println("544331 is greater than 544331 "
                           + intPredicate1.test(544331));
    }
}
輸出:
544331 is less than 544331 true
544331 is equal to 544331 true
544331 is less than equal to 544331 true
544331 is equal to 544331 true
544331 is greater than 544331 false

參考: https://docs.oracle.com/javase/8/docs/api/java/util/function/IntPredicate.html



相關用法


注:本文由純淨天空篩選整理自CharchitKapoor大神的英文原創作品 Java.util.function.IntPredicate interface in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。