下面的选项1或选项2是否正确(例如,一个优先于另一个)或它们是否相同?
选项1
collectionOfThings.
stream().
filter(thing -> thing.condition1() && thing.condition2())
或
选项2
collectionOfThings
.stream()
.filter(thing -> thing.condition1())
.filter(thing -> thing.condition2())
答案 0 :(得分:8)
要编译,第二个应该是
collectionOfThings.
stream().
filter(thing -> thing.condition1()).
filter(thing -> thing.condition2())
他们都是等同的。有时一个比另一个更可读。
编写第二种方法的另一种方法是使用方法参考:
collectionOfThings
.stream()
.filter(Thing::condition1)
.filter(Thing::condition2)
另请注意,约定是将点放在行的开头而不是结尾,就像编写项目符号列表一样。