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


Java IntStream allMatch()用法及代碼示例


IntStream allMatch(IntPredicate謂詞)返回此流的所有元素是否與提供的謂詞匹配。如果不一定要確定結果,則可能不會評估所有元素上的謂詞。這是短路端子操作。如果出現無限輸入時,端子操作可能會在有限時間內終止,則該端子操作會發生短路。
用法:

boolean allMatch(IntPredicate predicate)

Where, IntPredicate represents a predicate (boolean-valued function)
of one int-valued argument and the function returns true if either
all elements of the stream match the provided predicate or 
the stream is empty, otherwise false.

注意:如果流為空,則返回true,並且不評估謂詞。

示例1:allMatch()函數來檢查是否所有元素都可以被3整除。


// Java code for IntStream allMatch 
// (Predicate predicate) to check whether 
// all elements of this stream match 
// the provided predicate. 
import java.util.*; 
import java.util.stream.IntStream; 
  
class GFG { 
  
    // Driver code 
    public static void main(String[] args) 
    { 
  
        // Creating an IntStream 
        IntStream stream = IntStream.of(3, 5, 9, 12, 14); 
  
        // Check if all elements of stream 
        // are divisible by 3 or not using 
        // IntStream allMatch(Predicate predicate) 
        boolean answer = stream.allMatch(num -> num % 3 == 0); 
  
        // Displaying the result 
        System.out.println(answer); 
    } 
}

輸出:

false

示例2:allMatch()函數檢查將兩個IntStream串聯後獲得的IntStream中的所有元素是否小於2。

// Java code for IntStream allMatch 
// (Predicate predicate) to check whether 
// all elements of this stream match 
// the provided predicate. 
import java.util.*; 
import java.util.stream.IntStream; 
  
class GFG { 
  
    // Driver code 
    public static void main(String[] args) 
    { 
  
        // Creating an IntStream after concatenating 
        // two IntStreams 
        IntStream stream = IntStream.concat(IntStream.of(-2, -4, -6, -8), 
                                            IntStream.of(-1, 0, 1, 5)); 
  
        // Check if all elements of stream 
        // are less than 2 or not using 
        // IntStream allMatch(Predicate predicate) 
        boolean answer = stream.allMatch(num -> num < 2); 
  
        // Displaying the result 
        System.out.println(answer); 
    } 
}

輸出:

false

示例3:allMatch()函數,以顯示流是否為空,然後返回true。

// Java code for IntStream allMatch 
// (Predicate predicate) to check whether 
// any element of this stream match 
// the provided predicate. 
import java.util.*; 
import java.util.stream.IntStream; 
  
class GFG { 
  
    // Driver code 
    public static void main(String[] args) 
    { 
  
        // Creating an empty IntStream 
        IntStream stream = IntStream.empty(); 
  
        boolean answer = stream.allMatch(num -> true); 
  
        // Displaying the result 
        System.out.println(answer); 
    } 
}

輸出:

true


相關用法


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