java:减少 ​​vs anyMatch vs 包含

标签 java java-8 java-stream

 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/

相关文章:

java - 为什么正则表达式\w*(\s+|$) 找到 2 个匹配项 "foo"(Java)?

java - 解析超大 Excel 2007 文件的最佳语言

java - 使用 Java8 流 API 从集合中删除最大值(或最小值)

java - 如何使用 java.time.LocalDateTime 设置 jadira PersistentLocalDateTime?

java - 使用 java 8 流将字符串替换为 HashMap 值

java - JFreeChart 支持这种类型的条形图吗?

java - 如何从 map 中生成具有不同值的 map (并使用 BinaryOperator 使用正确的键)?

Java8 代码停止编译并让我进行不必要的显式转换

java - 从 map 列表列表中收集特定键的值 List<String,

Java 8 流 : Combine properties of two objects which are in ArrayLists into an ArrayList of a third object type