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


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


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

boolean allMatch(LongPredicate predicate)

參數:

  1. LongPredicate : 一個long值參數的謂詞(布爾值函數)。

返回值:如果流中的所有元素都與提供的謂詞匹配,或者流為空,則該函數返回true,否則返回false。


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

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

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

輸出:

false

示例2:allMatch()函數,用於檢查並置兩個LongStream之後獲得的LongStream中的所有元素是否小於2。

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

輸出:

false

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

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

輸出:

true


相關用法


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