Insert an element into a Stream in Java

In this article, we will discuss how to insert an element into a Stream in Java either at the beginning or at the end of the Stream.


 

1. Insert at beginning

The idea is to create a sequential Stream of given element using Stream.of() factory method and then use Stream.concat() for concatenating the resultant stream into the original Stream.

Please note that in order to insert the given element at the beginning, the resultant Stream from that element is passed as the first parameter to the Stream.concat() function.

Download   Run Code

Output:

[0, 1, 2, 3, 4]

 
We can also convert the Stream to a list and insert the specified element into the list at the very beginning, and then get back the Stream from that list.

 

Download   Run Code

Output:

[0, 1, 2, 3, 4]

 

2. Inserting at the end

To insert an element at the end of a Stream, we need to change the order in which the arguments were passed to Stream.concat() function. Now the resultant Stream from given element is passed as the second parameter to the Stream.concat() function.

 

Download   Run Code

Output:

[1, 2, 3, 4, 5]

Please note that this approach will only work for finite Streams. For Streams representing an infinite sequence, we will never get to the end of the Stream. This is illustrated here.

 
We can also convert the Stream to a list and insert the given element similar to approach discussed earlier, but even that doesn’t help in case of infinite Streams.

Download   Run Code

Output:

[1, 2, 3, 4, 5]

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz