从 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
Return a value from Java 8 forEach loop
提问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 forEach
method in a Collection
expects a Consumer
which 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 obj
is Object
:
我想在满足条件时跳出循环,最好使用简单的for(...)
循环。我假设的类型obj
是Object
:
for (Object obj : someObjects) {
if (some_condition_met) {
return true;
}
}
return false;
回答by Ousmane D.
forEach
accepts a Consumer
therefore 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);
}