Java 如何在可迭代对象上执行流函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20310209/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 00:59:08  来源:igfitidea点击:

How to perform Stream functions on an Iterable?

javajava-8java-streamiterablespliterator

提问by The Coordinator

In Java 8, the Streamclass does not have any method to wrap a an Iterable.

在 Java 8 中,Stream该类没有任何方法来包装 an Iterable

Instead, I am obtaining the Spliteratorfrom the Iterableand then obtaining a Streamfrom StreamSupportlike this:

相反,我正在Spliterator从中获取Iterable,然后StreamStreamSupport这样获取:

boolean parallel = true;

StreamSupport.stream(spliterator(), parallel)
                .filter(Row::isEmpty)
                .collect(Collectors.toList())
                .forEach(this::deleteRow);

Is there some other way of generating Streamoperations on an Iterablethat I am missing?

是否有其他方法可以StreamIterable我缺少的对象上生成操作?

采纳答案by Scott B

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);
}

回答by Jay

What you describe isthe 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.

您所描述的从 Iterable 获取流的方法。这就是他们将 spliterator() 方法添加到 Iterable 的原因。我自己也做过同样的转换,还没有看到另一种方式。

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

[更新] 也许这个其他答案会澄清“为什么”。

回答by dsingleton

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.

我知道这并不能直接回答您的问题,但是相当数量的 Iterable 源(例如集合)现在也具有将对象作为流获取的方法。

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).

我认为你会遇到这个问题的摩擦是 Iterable 在语义上是串行的,而 Spliterators 旨在用于并行处理。如果 JDK 中尚未提供,那么为您感兴趣的底层数据源实现 Spliterator 可能是一个更好的主意,因为仅使用 Iterable 的包装器将无法让您获得 Stream API 提供的好处(例如并行处理)。