Adding two Java 8 streams, or an extra element to a stream Ask Question

Adding two Java 8 streams, or an extra element to a stream Ask Question

I can add streams or extra elements, like this:

Stream stream = Stream.concat(stream1, Stream.concat(stream2, Stream.of(element));

And I can add new stuff as I go, like this:

Stream stream = Stream.concat(
                       Stream.concat(
                              stream1.filter(x -> x!=0), stream2)
                              .filter(x -> x!=1),
                                  Stream.of(element))
                                  .filter(x -> x!=2);

But this is ugly, because concat is static. If concat were an instance method, the above examples would be much easier to read:

 Stream stream = stream1.concat(stream2).concat(element);

And

 Stream stream = stream1
                 .filter(x -> x!=0)
                 .concat(stream2)
                 .filter(x -> x!=1)
                 .concat(element)
                 .filter(x -> x!=2);

My question is:

1) Is there any good reason why concat is static? Or is there some equivalent instance method I'm missing?

2) In any case, is there a better way of doing this?

ベストアンサー1

Unfortunately this answer is probably of little or no help whatsoever, but I did a forensics analysis of the Java Lambda Mailing list to see if I could find the cause of this design. This is what I found out.

In the beginning there was an instance method for Stream.concat(Stream)

In the mailing list I can clearly see the method was originally implemented as an instance method, as you can read in this thread by Paul Sandoz, about the concat operation.

In it they discuss the issues that could arise from those cases in which the stream could be infinite and what concatenation would mean in those cases, but I do not think that was the reason for the modification.

あなたはこの他のスレッドJDK 8 の初期のユーザーの中には、null 引数で使用されたときの concat インスタンス メソッドの動作について疑問を抱く人もいました。

これ他のスレッドしかし、concat メソッドの設計が議論中であったことが明らかになりました。

Streams.concat(Stream,Stream) にリファクタリングしました

しかし、何の説明もなく、突然、メソッドは静的メソッドに変更されました。ストリームの結合に関するこのスレッドこれはおそらくこの変更について少し明らかにした唯一のメールスレッドですが、リファクタリングの理由を判断するには十分ではありませんでした。しかし、コミットしたそこで彼らは、concatメソッドをヘルパー クラスから移動しStreamてヘルパー クラス内に入れることを提案しましたStreams

Stream.concat(Stream,Stream) にリファクタリングしました

後で、再び移動されましたからStreamsまでですStreamが、やはりこれについても説明がありません。

つまり、結局のところ、この設計の理由は私には完全には明らかではなく、良い説明も見つけられませんでした。メーリング リストで質問することはまだできると思います。

ストリーム連結の代替案

これMichael Hixson による他のスレッドストリームを結合/連結する他の方法について議論/質問する

  1. 2 つのストリームを結合するには、次のようにします。

    Stream.concat(s1, s2)
    

    これではない:

    Stream.of(s1, s2).flatMap(x -> x)
    

    ... 右?

  2. 2 つ以上のストリームを結合するには、次のようにします。

    Stream.of(s1, s2, s3, ...).flatMap(x -> x)
    

    これではない:

    Stream.of(s1, s2, s3, ...).reduce(Stream.empty(), Stream::concat)
    

    ... 右?

おすすめ記事