我想使用
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));
}
我不想使用...
.toList()
,因为我想Java 8 Streams 的短路如何工作?.reduce()
,因为 Java 8 Streams 的短路如何工作?我想,我必须使用
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。
您可以尝试使用
anyMatch()
。
private static boolean testMethod(Stream<String> stream) {
return !stream.anyMatch(text -> !"match".equals(text));
}
对于空的
false
,它将返回 Stream
,因为流中没有不等于 "match"
的项目