当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。