[Java] Stream管線操作觀念探討

Stream就如同一個迭代器(Iterator),單向不可往復,數據只能探取一次,探取一次後便用盡了。

詳細內容可繼續往下看。

 

Stream管線操作觀念

使用Stream進行管線操作(pipeline),類似流水從數據面前流過,一去不復返,不可逆。

Stream只能迭代一次,重複對Stream迭代,會造成IllegalStateException例外。

下方舉例若重複使用會發生什麼事情。

 

Stream管線操作實作練習

import java.util.stream.IntStream;
import java.util.stream.Stream;

public class CharSequenceDemo {

    public static void main(String[] args) {

        String testString = "String";
        IntStream intStream = testString.chars();
        intStream.forEach(n -> System.out.print(n + " "));
        System.out.println();

        Stream<Character> characterStream = testString.chars()
                .mapToObj(c -> (char) c);     
        characterStream.forEach(n -> System.out.print(n + " "));
        System.out.println();
    }
}

 

Stream characterStream = testString.chars()

若將testString.chars()改成intStream,會產生下列錯誤。

Exception in thread "main" java.lang.IllegalStateException: stream has already been operated upon or closed
at java.util.stream.AbstractPipeline.(AbstractPipeline.java:203)
at java.util.stream.ReferencePipeline.(ReferencePipeline.java:94)
at java.util.stream.ReferencePipeline$StatelessOp.(ReferencePipeline.java:618)
at java.util.stream.IntPipeline$4.(IntPipeline.java:244)
at java.util.stream.IntPipeline.mapToObj(IntPipeline.java:243)
at com.main.CharSequenceDemo.main(CharSequenceDemo.java:17)
/Users/eyes/Library/Caches/NetBeans/9.0/executor-snippets/run.xml:111: The following error occurred while executing this line:
/Users/eyes/Library/Caches/NetBeans/9.0/executor-snippets/run.xml:94: Java returned: 1
BUILD FAILED (total time: 0 seconds)

從錯誤訊息可以知道,IntStream的物件已經在intStream.forEach(n -> System.out.print(n + " "))被用掉了。

若再次使用,已經沒有IntStream物件,所以會拋出java.lang.IllegalStateException。