[英]Java 8: how to get the first number greater than 10 in a stream?
As per subject: How can I get the first number greater than 10 in a stream? 按照主题:如何获得流中第一个大于10的数字?
Is there any method of stream()
that may help in this case? 在这种情况下,是否有任何
stream()
方法可能会有所帮助?
I would like that as soon as the stream reaches the first element above 10 it will return it without looping the rest. 我希望流一旦到达第一个大于10的元素,它将返回它而不循环其余的元素。 (kind of "break" the loop) Is it possible?
(有点“打破”循环)可能吗?
You're probably looking for filter
and findFirst
: 您可能正在寻找
filter
和findFirst
:
// new Random().ints() // or whatever the stream is
.filter(i -> i > 10).findFirst();
findFirst
returns some type of Optional
, so you need to decide what to do with it if you don't find a match. findFirst
返回某种类型的Optional
,因此,如果找不到匹配Optional
,则需要决定如何处理它。
This is similar to a loop like this: 这类似于这样的循环:
for (int i : ...)
if (i > 10) // "filter"
return i; // "findFirst" (may or may not be present)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.