使用Java 8 JDK將Iterable轉換爲Stream

本文翻譯自:Convert Iterable to Stream using Java 8 JDK

I have an interface which returns java.lang.Iterable<T> . 我有一個返回java.lang.Iterable<T>的接口。

I would like to manipulate that result using the Java 8 Stream API. 我想使用Java 8 Stream API處理該結果。

However Iterable can't "stream". 但是Iterable無法“流式傳輸”。

Any idea how to use the Iterable as a Stream without converting it to List? 任何想法如何將Iterable用作流而不轉換爲List?


#1樓

參考:https://stackoom.com/question/1cPoz/使用Java-JDK將Iterable轉換爲Stream


#2樓

You can easily create a Stream out of an Iterable or Iterator : 您可以使用IterableIterator輕鬆創建Stream

public static <T> Stream<T> stream(Iterable<T> iterable) {
    return StreamSupport.stream(
        Spliterators.spliteratorUnknownSize(
            iterable.iterator(),
            Spliterator.ORDERED
        ),
        false
    );
}

#3樓

There's a much better answer than using spliteratorUnknownSize directly, which is both easier and gets a better result. spliteratorUnknownSize直接使用spliteratorUnknownSize相比,有一個更好的答案,這既簡單又得到更好的結果。 Iterable has a spliterator() method, so you should just use that to get your spliterator. Iterable具有spliterator()方法,因此您應該使用該方法來獲取您的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). 在最壞的情況下,它是相同的代碼(默認實現使用spliteratorUnknownSize ),但是在更常見的情況下,如果您的Iterable已經是一個集合,您將獲得更好的分離器,從而獲得更好的流性能(甚至可能具有良好的並行性) )。 It's also less code: 它的代碼也更少:

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

As you can see, getting a stream from an Iterable (see also this question ) is not very painful. 如您所見,從Iterable獲得流(也請參見此問題 )不是很痛苦。


#4樓

我想建議使用JOOL庫,它在Seq.seq(iterable)調用後隱藏了分隔符魔術,並且還提供了許多其他有用的功能。


#5樓

I've created this class: 我創建了此類:

public class Streams {
    /**
     * Converts Iterable to stream
     */
    public static <T> Stream<T>  streamOf(final Iterable<T> iterable) {
        return toStream(iterable, false);
    }

    /**
     * Converts Iterable to parallel stream
     */
    public static <T> Stream<T> parallelStreamOf(final Iterable<T> iterable) {
        return toStream(iterable, true);
    }

    private static <T> Stream<T> toStream(final Iterable<T> iterable, final boolean isParallel) {
        return StreamSupport.stream(iterable.spliterator(), isParallel);
    }
}

I think it's perfectly readable because you don't have to think about spliterators and booleans (isParallel). 我認爲它是完全可讀的,因爲您不必考慮分隔符和布爾值(isParallel)。


#6樓

如果您可以使用Guava庫(從21版開始),則可以使用

Streams.stream(iterable)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章