包含takeWhile()for Streams [英] Inclusive takeWhile() for Streams

查看:98
本文介绍了包含takeWhile()for Streams的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有办法添加针对方法takeWhile()的条件测试的流的最后一个元素。我相信我想要实现类似于RxJava的takeUntil()方法。

I want to know if there is a way to add the last element of the stream that was tested against the condition of the method takeWhile(). I believe I want to achieve something similar to RxJava's takeUntil() method.

我猜测没有直接的方法可以做到这一点(如果我弄错了,请纠正我) ,但我想知道是否有一个正确的解决方法来实现这一点,我现在知道了。

I'm guessing there is no direct way to do this (correct me if I am mistaken), but I would like to know if there is a proper workaround to achieve this that I am now aware of.

我在Stackoverflow中搜索但几乎没有成功。如果您认为有线程可以解决我的问题,我当然希望看到它。

I've searched throughout Stackoverflow with little to no success. If you think there are threads that could solve my problems, I would certainly like to see it.

如果您查看以下代码的peek(),您会看到数字5是根据takeWhile()条件检查的,但它永远不会到达forEach():

If you look at the following code's peek() you will see that the number 5 is checked against the takeWhile() condition but it never arrives in the forEach():

IntStream.of(1, 3, 2, 5, 4, 6)
        .peek(foo -> System.out.println("Peek: " + foo))
        .takeWhile(n -> n < 5)
        .forEach(bar -> System.out.println("forEach: " + bar));

预期结果是针对takeWhile条件检查的最后一个元素到达forEach的System.out: :的println。在这种情况下它是5。

The expected result is for the last element checked against takeWhile's condition to arrive at the forEach's System.out::println. In this case it is 5.

感谢大家!

推荐答案

使用普通流API没有方便的方法。有可能在丑陋的方式(您需要调整此实现,这只是一个正常的 takeWhile 为Java 8backported。

There's no convenient way to do that with the normal stream API. It is possible in an ugly way (you would need to adapt this implementation, that's just a normal takeWhile "backported" for Java 8).

这个人编写了一个流扩展库,其中包含 takeWhileInclusive

This guy has written a stream extension library which has takeWhileInclusive.

样本用法:

IntStreamEx.of(1, 3, 2, 5, 4, 6)
    .peek(foo -> System.out.println("Peek: " + foo))
    .takeWhileInclusive(n -> n < 5)
    .forEach(bar -> System.out.println("forEach: " + bar));

这篇关于包含takeWhile()for Streams的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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