如何实现Java流? [英] How to implement a Java stream?

查看:97
本文介绍了如何实现Java流?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实现一个 Stream< T>

我不想只使用实现Stream< T> ,因为我必须实现大量的方法。

I don't want to just use implements Stream<T>, because I would have to implement a ton of methods.

这可以避免吗?

更具体一点,我如何流 t1 t2 t3 例如:

To be more concrete, how can I stream t1, t2 and t3 for example:

class Foo<T> {
    T t1, t2, t3;

    Foo(T t1, T t2, T t3) {
        this.t1 = t1;
        this.t2 = t2;
        this.t3 = t3;
    }
}


推荐答案

JDK的标准实现 Stream 是内部类 java.util.stream.ReferencePipeline ,你无法直接实例化它。

The JDK's standard implementation of Stream is the internal class java.util.stream.ReferencePipeline, you cannot instantiate it directly.

相反,您可以使用 java.util.stream.Stream.builder() java.util.stream.StreamSupport.stream(Spliterator< T>,boolean)和各种 1 2 其他静态工厂方法,用于创建默认实现的实例。

Instead you can use java.util.stream.Stream.builder(), java.util.stream.StreamSupport.stream(Spliterator<T>, boolean) and various1, 2 other static factory methods to create an instance of the default implementation.

使用spliterator可能是最强大的方法,因为它允许您懒惰地提供对象,同时如果您的源可以分成多个块,还可以实现高效的并行化。

Using a spliterator is probably the most powerful approach as it allows you to provide objects lazily while also enabling efficient parallelization if your source can be divided into multiple chunks.

此外,您还可以将流转换回分裂器,将它们包装在自定义分裂器中,然后在需要实现自己的有状态中间操作时将它们转换回流 - 例如由于标准API中的缺点 - 因为大多数可用的中间操作不允许有状态。请参阅此SO答案例如。

Additionally you can also convert streams back into spliterators, wrap them in a custom spliterator and then convert them back into a stream if you need to implement your own stateful intermediate operations - e.g. due to shortcomings in the standard APIs - since most available intermediate ops are not allowed to be stateful.
See this SO answer for an example.

原则上你可以编写自己的流接口实现,但这将非常繁琐。

In principle you could write your own implementation of the stream interface, but that would be quite tedious.

这篇关于如何实现Java流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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