通过谓词限制流 [英] Limit a stream by a predicate

查看:21
本文介绍了通过谓词限制流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有 Java 8 流操作限制(可能是无限的)Stream 直到第一个元素无法匹配谓词?

Is there a Java 8 stream operation that limits a (potentially infinite) Stream until the first element fails to match a predicate?

在 Java 9 中,我们可以使用 takeWhile 如下例所示打印所有小于 10 的数字.

In Java 9 we can use takeWhile as in the example below to print all the numbers less than 10.

IntStream
    .iterate(1, n -> n + 1)
    .takeWhile(n -> n < 10)
    .forEach(System.out::println);

由于 Java 8 中没有这样的操作,那么以通用方式实现它的最佳方法是什么?

As there is no such operation in Java 8, what's the best way of implementing it in a general way?

推荐答案

操作 takeWhiledropWhile 已添加到 JDK 9.您的示例代码

Operations takeWhile and dropWhile have been added to JDK 9. Your example code

IntStream
    .iterate(1, n -> n + 1)
    .takeWhile(n -> n < 10)
    .forEach(System.out::println);

在 JDK 9 下编译和运行时,其行为将完全符合您的预期.

will behave exactly as you expect it to when compiled and run under JDK 9.

JDK 9 已经发布.可在此处下载:JDK 9 Releases.

JDK 9 has been released. It is available for download here: JDK 9 Releases.

这篇关于通过谓词限制流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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