If you’re working with Spring, check out "REST With Spring":


1. Overview

In this quick article, we’re going to take a look at how to add an element to a Java 8 Stream which is not as intuitive as adding an element to a normal collection.

2. Prepending

We can easily prepend a given element to a Stream by invoking the static Stream.concat() method:

public void givenStream_whenPrependingObject_thenPrepended() {
    Stream<Integer> anStream = Stream.of(1, 2, 3, 4, 5);

    Stream<Integer> newStream = Stream.concat(Stream.of(99), anStream);

    assertEquals(newStream.findFirst().get(), (Integer) 99);

3. Appending

Likewise, to append an element to the end of a Stream, we just need to invert the arguments.

Keep in mind that Streams can represent infinite sequences so there are scenarios when you might never get to your new element:

public void givenStream_whenAppendingObject_thenAppended() {
    Stream<String> anStream = Stream.of("a", "b", "c", "d", "e");

    Stream<String> newStream = Stream.concat(anStream, Stream.of("A"));

    List<String> resultList = newStream.collect(Collectors.toList());
    assertEquals(resultList.get(resultList.size() - 1), "A");

4. At a Specific Index

This operation is not fully supported by Stream API because essentially Streams are not collections and do not recognize the concept of indexes.

So, in order to do this, we need to convert the Stream to a list, then insert the element, and finally, get a Stream from that new list.

Keep in mind that this will give you the desired result, but you will also lose the laziness of a Stream because we need to consume it before inserting a new element.

Let’s create a utility method to do the heavy work:

public <T> Stream<T> insertInStream(Stream<T> stream, T elem, int index) {
    List<T> result = stream.collect(Collectors.toList());
    result.add(index, elem);
    return result.stream();

Now, let’s test our code to ensure everything is working as expected:

public void givenStream_whenInsertingObject_thenInserted() {
    Stream<Double> anStream = Stream.of(1.1, 2.2, 3.3);

    Stream<Double> newStream = insertInStream(anStream, 9.9, 3);

    List<Double> resultList = newStream.collect(Collectors.toList());
    assertEquals(resultList.get(3), (Double) 9.9);

5. Conclusion

In this short article, we’ve seen how to add a single element to a Stream, be it at the beginning, at the end, or at a given position.

Keep in mind that although prepending an element works for any Stream, adding it to the end or at a specific index only works for finite streams.

As always, complete source code can be found over on Github.

The new Certification Class of "REST With Spring" is finally out: