LoginSignup
1
2

More than 5 years have passed since last update.

Java Stream は再利用できない。

Last updated at Posted at 2017-09-05

再利用できませんでした。

import java.util.stream.*;

public class StreamTest {

    public static void main(String[] args) {

        // a-z のストリーム作成
        Stream<String> stream = Stream.iterate('a', c -> ++c).map(Object::toString).limit('z' - 'a' + 1);

        // stream初利用
        try {
            String collect_01 = stream.filter(str -> {
                byte[] b = str.getBytes();
                return (b[0] % 2 == 0);
            }).collect(Collectors.joining(";"));
            System.out.println(collect_01);
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }

        // stream再利用 -- 失敗する
        try {
            String collect_02 = stream.map(str -> "[" + str + "]").collect(Collectors.joining(";"));
            System.out.println(collect_02);
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }

    }

}

結果

  • [stream has already been operated upon or closed]というエラーがでました。
b;d;f;h;j;l;n;p;r;t;v;x;z
stream has already been operated upon or closed
  • 処理つつ、カウントしつつ云々とかするには、なんでもかんでもstreamじゃないほうがいいのかな〜?
1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2