List<Boolean> results = new ArrayList<>();
results.add(true);
results.add(true);
results.add(true);
results.add(false);
if (results.contains(false)) {
System.out.println(false);
} else {
System.out.println(true);
}
System.out.println(results.stream().reduce((a, b) -> a && b).get());
//System.out.println(!results.stream().anyMatch(a -> a == false));
System.out.println(!results.stream().anyMatch(a -> !a));
输出:
假的
假的
假的
仅供引用,结果是 map+collect 操作的结果
List<Job> jobs;
List<Boolean> results = job.stream().map(j -> j.ready()).collect(Collector.toList())
如果我选择 reduce 或 anyMatch,我就不必从 map 操作中收集结果。
从 boolean 值列表的结果中,如果至少有一个 false,我只想返回 false。
我可以通过 reduce 或 anyMatch 来完成。我有点不喜欢 reduce 中的 Optional,我有点不喜欢我必须否定任何匹配
使用这两者有什么优缺点吗?
最佳答案
看起来您将 boolean 值收集到列表中的唯一原因是您可以检查某些是否为 false
:
If I choose either reduce or anyMatch, I don't have to collect the results from map operation [...] I just want to return false if there is at least one false.
如果是这种情况,那么您绝对应该考虑直接的基于流的方法:
return jobs.stream().allMatch(Job::ready);
关于java:减少 vs anyMatch vs 包含,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55526533/