从 Java 8 forEach 循环返回一个值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47005602/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 02:32:10  来源:igfitidea点击:

Return a value from Java 8 forEach loop

javajava-8

提问by Punter Vicky

In the below example , someObjects is a set. I am trying to return true if a condition matches within the loop , however this doesn't seem to compile. However when I just add "return" it works fine.What is the issue that I need to fix?

在下面的例子中, someObjects 是一个集合。如果循环中的条件匹配,我试图返回 true ,但这似乎无法编译。但是,当我添加“return”时它工作正常。我需要解决什么问题?

public boolean find(){

    someObjects.forEach(obj -> {
       if (some_condition_met) {
          return true;
       }
    });

    return false;
}

Compilation Errors

编译错误

The method forEach(Consumer) in the type Iterable is not applicable for the arguments (( obj) -> {})

Iterable 类型中的 forEach(Consumer) 方法不适用于参数 (( obj) -> {})

采纳答案by pablochan

The forEachmethod in a Collectionexpects a Consumerwhich means a function that takes a value, but doesn't return anything. That's why you can't use return true;but a return;works fine.

a 中的forEach方法Collection需要 a Consumer,这意味着函数接受一个值,但不返回任何内容。这就是为什么你不能使用return true;但 areturn;工作正常的原因。

I you want to break out of the loop when your condition is met, it's better to use a simple for(...)loop. I assumed that the type of objis Object:

我想在满足条件时跳出循环,最好使用简单的for(...)循环。我假设的类型objObject

for (Object obj : someObjects) {
  if (some_condition_met) {
    return true;
  }
}

return false;

回答by Ousmane D.

forEachaccepts a Consumertherefore you cannot pass in a behaviour that does not return void. you need to do something like:

forEach接受 aConsumer因此您不能传递不返回void的行为。您需要执行以下操作:

return someObjects.stream().anyMatch(e -> condition);

回答by Jason Hu

I guess you want to do this:

我猜你想这样做:

public boolean find(){
    return someObjects.stream().anyMatch(o -> your_condition);
}