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


Java Stream noneMatch()用法及代码示例


流noneMatch(谓词谓词)返回此流中是否没有元素与提供的谓词匹配。如果不一定要确定结果,则可能不会评估所有元素上的谓词。这是短路端子操作。如果出现无限输入时,端子操作可能会在有限时间内终止,则该端子操作会发生短路。
用法:

boolean noneMatch(Predicate<? super T> predicate)

Where, T is the type of the input to the predicate
and the function returns true if either no elements 
of the stream match the provided predicate or the
stream is empty, otherwise false.

注意:如果流为空,则返回true,并且不评估谓词。

示例1:要检查是否没有长度为4的字符串。


// Java code for Stream noneMatch 
// (Predicate predicate) to check whether 
// no elements of this stream match 
// the provided predicate. 
import java.util.stream.Stream; 
  
class GFG { 
  
    // Driver code 
    public static void main(String[] args) 
    { 
  
        // Creating a Stream of Strings 
        Stream<String> stream = Stream.of("CSE", "C++", 
                                        "Jav", "DS"); 
  
        // Using Stream noneMatch(Predicate predicate) 
        boolean answer = stream.noneMatch(str -> (str.length() == 4)); 
  
        // Displaying the result 
        System.out.println(answer); 
    } 
}
输出:
true

示例2:检查是否有不小于0的元素。

// Java code for Stream noneMatch 
// (Predicate predicate) to check whether 
// no elements of this stream match 
// the provided predicate. 
import java.util.*; 
  
class GFG { 
  
    // Driver code 
    public static void main(String[] args) 
    { 
  
        // Creating a list of Integers 
        List<Integer> list = Arrays.asList(4, 0, 6, 2); 
  
        // Using Stream noneMatch(Predicate predicate) 
        boolean answer = list.stream().noneMatch(num -> num < 0); 
  
        // Displaying the result 
        System.out.println(answer); 
    } 
}
输出:
true

示例3:检查在所需位置是否没有带有必需字符的元素。

// Java code for Stream noneMatch 
// (Predicate predicate) to check whether 
// no elements of this stream match 
// the provided predicate. 
import java.util.stream.Stream; 
  
class GFG { 
  
    // Driver code 
    public static void main(String[] args) 
    { 
  
        // Creating a Stream of Strings 
        Stream<String> stream = Stream.of("Geeks", "fOr", 
                                        "GEEKSQUIZ", "GeeksforGeeks", "CSe"); 
  
        // Using Stream noneMatch(Predicate predicate) 
        boolean answer = stream.noneMatch 
                         (str -> Character.isUpperCase(str.charAt(1))  
                         && Character.isLowerCase(str.charAt(2))  
                         && str.charAt(0) == 'f'); 
  
        // Displaying the result 
        System.out.println(answer); 
    } 
}
输出:
false


相关用法


注:本文由纯净天空筛选整理自Sahil_Bansall大神的英文原创作品 Stream noneMatch() method in Java with examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。