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


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。