【问题标题】:Java 8 Streams Filter Intention of Lazy Evaluation [duplicate]Java 8 Streams过滤器延迟评估的意图[重复]
【发布时间】:2016-07-30 21:52:21
【问题描述】:

下面的选项 1 或选项 2 是否正确(例如,一个优先于另一个)或它们是否等效?

选项 1

collectionOfThings.
    stream().
    filter(thing -> thing.condition1() && thing.condition2())

选项 2

collectionOfThings
    .stream()
    .filter(thing -> thing.condition1())
    .filter(thing -> thing.condition2())

【问题讨论】:

  • 上一个问题的答案是错误的。我不是基准测试专家,但我自己的测试表明 Option1 的性能要好得多。我会将我的测试代码发布到另一个问题,如果有人对我的发现进行审查,我将不胜感激。

标签: java java-8 java-stream


【解决方案1】:

要编译,第二个应该是

collectionOfThings.
    stream().
    filter(thing -> thing.condition1()).
    filter(thing -> thing.condition2())

它们都是等价的。有时一个比另一个更具可读性。

另一种编写第二种方法是使用方法引用:

collectionOfThings
    .stream()
    .filter(Thing::condition1)
    .filter(Thing::condition2)

另请注意,惯例是将点放在行首而不是行尾,就像您编写项目符号列表一样。

【讨论】:

  • 谢谢!我调整了示例以修复错误。
猜你喜欢
  • 2018-04-14
  • 1970-01-01
  • 2016-09-12
  • 2021-05-17
  • 2018-01-01
  • 2014-07-26
相关资源
最近更新 更多