How to perform Stream functions on an Iterable? [duplicate]

岁酱吖の 提交于 2019-11-30 05:43:13

My similar question got marked as duplicate, but here is the helper methods I've used to avoid some of the boilerplate:

public static <T> Stream<T> stream(Iterable<T> in) {
    return StreamSupport.stream(in.spliterator(), false);
}

public static <T> Stream<T> parallelStream(Iterable<T> in) {
    return StreamSupport.stream(in.spliterator(), true);
}
Jay

What you describe is the way to get a stream from an Iterable. That's why they added the spliterator() method to Iterable. I've done the same conversion myself and have not seen another way.

[UPDATE] Maybe this other answer will shed some clarification on the "why."

I know this doesn't directly answer your question, but a decent number of Iterable sources such as collections now have a method to get the object as a stream as well.

I think that the friction that you will run into with this question is that Iterable is semantically serial whereas Spliterators are meant to be used for processing in parallel. It is probably a better idea to implement a Spliterator for the underlying data source that you are interested in if it is not already provided in the JDK because just using a wrapper around the Iterable will not allow you to gain the benefits that the Stream API provide (such as parallel processing).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!