To add an object to the beginning of a list using Java Streams, we typically cannot directly prepend an object in a stream-friendly way because Streams themselves are immutable and don’t directly modify the original collection. However, we can achieve this by creating a new list with the desired order.
Here’s how we can approach it:
package org.kodejava.stream;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class StreamBeginningAdd {
public static void main(String[] args) {
List<String> originalList = Arrays.asList("B", "C", "D");
String newElement = "A";
// Add the new element at the beginning using Stream
List<String> updatedList = Stream.concat(Stream.of(newElement), originalList.stream())
.collect(Collectors.toList());
// Output: [A, B, C, D]
System.out.println(updatedList);
}
}
Explanation:
- Stream.of(newElement): Wraps the new element as a single-element stream.
- originalList.stream(): Converts the existing list into a stream.
- Stream.concat(): Combines the two streams — placing the
newElement
stream first and the original list’s stream second. - collect(Collectors.toList()): Materializes (collects) the combined stream into a new list.
This ensures immutability of the original list and creates a new list with the desired order.