简体   繁体   English

Java 8:如何在流中获取大于10的第一个数字?

[英]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 : 您可能正在寻找filterfindFirst

// 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.

相关问题 如何比较 java 中的第一个日期应该大于第二个日期? - How to compare First Date should be greater than second date in java? 在java中删除大于99的以10为基数的正整数的最后两位数字 - Removes the last two digits of a positive integer base 10 number that is greater than 99 in java 大于256个android文件输出流 - Have a greater number than 256 android file output stream Java中的ConcurrentHashMap中,锁的数量是否可能大于存储桶的数量? - Is it possible to have number of locks greater than number of buckets in ConcurrentHashMap in Java? 如何使用Java在MongoDB中获取小于或大于某些值的文档 - How to get Documents less than or greater than some value in mongodb using java 如何在数组中显示大于/小于用户编号的随机值? - 爪哇 - How to display random values in an array that are greater/less than the user's number? - Java 如何使用java在控制台中的excel表中使用poi(2.5)打印大于7位的数字 - How to print a number greater than 7 digits using poi(2.5) from excel sheet in the console using java 如何在java中传递大于999 999 999的数字作为参数 - How can I pass number greater than 999 999 999 as parameter in java oracle-我们如何获得大于或等于的最小数字值 - oracle - How do we get the smallest number value that is greater than or equal Java:查找数组中大于零的最小数 - Java: Finding the smallest greater than zero number in an array
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM