How to Add Element to a Stream in Java


How can we add an element to a stream in Java?

Adding an element to a stream is not quite as simple as adding an element to a collection.

Suppose we have this stream of two strings:

Stream<String> s = Stream.of("b", "c");

Prepending to a stream

First, let’s try to prepand "a" to this stream to make "a", "b", "c".

We can use Stream.concat() to concatenate two streams.

We can wrap the element we will add inside a stream and merge the two streams.

Stream<String> s1 = Stream.concat(Stream.of("a"), s);

Appending to a stream

Let’s try to append "d" to this stream to make "b", "c", "d".

Let’s use Stream.concat() again.

Stream<String> s1 = Stream.concat(s, Stream.of("d"));

Note that streams can represent infinite sequences, so appending to an infinite stream means we may never reach this element.

Adding to a stream at an index

Let’s try to append "z" to this stream at index 1 to make "b", "z", "c".

It’s important to note that streams do not inherently understand indexes as collections do, so this functionality is not supported.

However, we can convert this stream into a collection, insert the new element, and convert back to a stream.

List<String> temp = s.collect(Collectors.toList());
temp.add(1, "z"); // add(index, element)
Stream<String> s1 = temp.stream();