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

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

问题描述

Iterable 上使用外部迭代时,我们使用 break 或<$ c从增强型for-each循环返回$ c> return :

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
   }
}

我们如何 break 使用Java 8 lambda表达式中的内部迭代返回,如:

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流中断或返回每个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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