使用 Java 8 JDK 将 Iterable 转换为 Stream [英] Convert Iterable to Stream using Java 8 JDK

查看:38
本文介绍了使用 Java 8 JDK 将 Iterable 转换为 Stream的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个返回 java.lang.Iterable 的接口.

I have an interface which returns java.lang.Iterable<T>.

我想使用 Java 8 Stream API 操作该结果.

I would like to manipulate that result using the Java 8 Stream API.

但是 Iterable 不能流式传输".

However Iterable can't "stream".

知道如何将 Iterable 用作流而不将其转换为 List 吗?

Any idea how to use the Iterable as a Stream without converting it to List?

推荐答案

有一个比直接使用 spliteratorUnknownSize 更好的答案,它既容易又得到更好的结果.Iterable 有一个 spliterator() 方法,所以你应该使用它来获取你的拆分器.在最坏的情况下,它是相同的代码(默认实现使用 spliteratorUnknownSize),但在更常见的情况下,你的 Iterable 已经是一个集合,你会得到更好的分离器,因此更好的流性能(甚至可能是良好的并行性).代码也更少:

There's a much better answer than using spliteratorUnknownSize directly, which is both easier and gets a better result. Iterable has a spliterator() method, so you should just use that to get your spliterator. In the worst case, it's the same code (the default implementation uses spliteratorUnknownSize), but in the more common case, where your Iterable is already a collection, you'll get a better spliterator, and therefore better stream performance (maybe even good parallelism). It's also less code:

StreamSupport.stream(iterable.spliterator(), false)
             .filter(...)
             .moreStreamOps(...);

如您所见,从 Iterable 获取流(另请参阅 这个问题) 不是很痛苦.

As you can see, getting a stream from an Iterable (see also this question) is not very painful.

这篇关于使用 Java 8 JDK 将 Iterable 转换为 Stream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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