中断或从 Java 8 流 forEach 返回? [英] Break or return from Java 8 stream forEach?

查看:77
本文介绍了中断或从 Java 8 流 forEach 返回?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当在 Iterable 上使用外部迭代时,我们使用增强的 for-each 循环中的 breakreturn 作为:

When using external iteration over an Iterable we use break or return from enhanced for-each loop as:

for (SomeObject obj : someObjects) {
   if (some_condition_met) {
      break; // or return obj
   }
}

我们如何在 Java 8 lambda 表达式中使用 内部迭代breakreturn,例如:

How can we break or return using the internal iteration in a Java 8 lambda expression like:

someObjects.forEach(obj -> {
   //what to do here?
})

推荐答案

如果你需要这个,你不应该使用 forEach,而是流上可用的其他方法之一;哪一个,取决于你的目标是什么.

If you need this, you shouldn't use forEach, but one of the other methods available on streams; which one, depends on what your goal is.

例如,如果这个循环的目标是找到匹配某个谓词的第一个元素:

For example, if the goal of this loop is to find the first element which matches some predicate:

Optional<SomeObject> result =
    someObjects.stream().filter(obj -> some_condition_met).findFirst();

(注意:这不会迭代整个集合,因为流是惰性求值的——它会在第一个匹配条件的对象处停止.

(Note: This will not iterate the whole collection, because streams are lazily evaluated - it will stop at the first object that matches the condition).

如果您只想知道集合中是否存在条件为真的元素,您可以使用anyMatch:

If you just want to know if there's an element in the collection for which the condition is true, you could use anyMatch:

boolean result = someObjects.stream().anyMatch(obj -> some_condition_met);

这篇关于中断或从 Java 8 流 forEach 返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆