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

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

问题描述

我想实现一个Stream.

我不想只使用 implements Stream,因为我必须实现大量的方法.

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

这能避免吗?

更具体地说,我如何流式传输 t1t2t3 例如:

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)和各种12 其他静态工厂方法来创建默认实现的实例.

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.

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

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天全站免登陆