How to Add a Single Element to a Stream

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:

@Test
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:

@Test
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:

@Test
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.

Related posts:

Jackson – Marshall String to JsonNode
Java Program to Generate Randomized Sequence of Given Range of Numbers
Java Program to Find the Minimum Element of a Rotated Sorted Array using Binary Search approach
Introduction to Netflix Archaius with Spring Cloud
Java Program to Find a Good Feedback Vertex Set
Functional Interfaces in Java 8
Java Program to Implement Expression Tree
Java Program to Implement WeakHashMap API
Java 9 Stream API Improvements
Java Program to Implement Kosaraju Algorithm
A Quick Guide to Using Keycloak with Spring Boot
Convert a Map to an Array, List or Set in Java
Rest Web service: Filter và Interceptor với Jersey 2.x (P1)
Spring Cloud AWS – EC2
Java Program to Perform String Matching Using String Library
Using the Not Operator in If Conditions in Java
Java Program to Implement Binary Search Tree
Java Program to Check if a Given Set of Three Points Lie on a Single Line or Not
Generating Random Numbers in a Range in Java
Java IO vs NIO
Getting Started with Stream Processing with Spring Cloud Data Flow
Collect a Java Stream to an Immutable Collection
How to Break from Java Stream forEach
Java Program to Implement Ternary Search Algorithm
Java Program to Implement Hamiltonian Cycle Algorithm
Java Program to Implement the linear congruential generator for Pseudo Random Number Generation
Different Ways to Capture Java Heap Dumps
Java Program to Implement Insertion Sort
Java Program to Implement Gauss Jordan Elimination
Spring Boot - Enabling HTTPS
Guide to the Volatile Keyword in Java
Java Program to Implement the Program Used in grep/egrep/fgrep