This article will discuss how to insert an element to a stream in Java either at the beginning or the end of the stream.

1. Inserting at the beginning

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

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

Download  Run Code

Output:

[0, 1, 2, 3, 4]

 
We can also convert the stream to a list, insert the specified element into the list initially, 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 the Stream.concat() method. Now the resultant stream from the given element is passed as the second parameter to the Stream.concat() method.

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’ll never get to the end of it. This is demonstrated here.

 
We can also convert the stream to a list and insert the given element similar to the earlier approach, but even that doesn’t help in infinite streams.

Download  Run Code

Output:

[1, 2, 3, 4, 5]

That’s all about inserting an element into a Stream in Java.