如何使用 Stream.allMatch() 对空流返回 false?

问题描述 投票:0回答:1

我想使用

Stream.allMatch()
,但当流为空时我需要
false

public static void main (String[] args) throws java.lang.Exception
{
   System.out.println(testMethod(Stream.empty())); // <- expected false (but is true)
   System.out.println(testMethod(Stream.of("match", "match"))); // <- expected true
   System.out.println(testMethod(Stream.of("match", "no match"))); // <- expected false
}
    
private static boolean testMethod(Stream<String> stream) {
   return stream.allMatch(text -> "match".equals(text));
}

https://ideone.com/8Nsjiw

我不想使用...

我想,我必须使用

noMatch()
,但我没有得到否定正确工作。

private static boolean testMethod(Stream<String> stream) {
   // my guess, but the results are wrong
   return !stream.noneMatch(text -> !"match".equals(text));
}

这不是如果使用 Stream.allMatch(),如何为空列表返回 false? 的重复,因为我使用

Stream
s 而不是
List
s。

java java-stream
1个回答
0
投票

您可以尝试使用

anyMatch()

private static boolean testMethod(Stream<String> stream) {
   return !stream.anyMatch(text -> !"match".equals(text));
}

对于空的

false
,它将返回
Stream
,因为流中没有不等于
"match"

的项目
© www.soinside.com 2019 - 2024. All rights reserved.