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

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

问题描述

我有一个返回 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作为Stream而不将其转换为List?

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

推荐答案

有一个比使用<$ c更好的答案$ c> 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天全站免登陆