is there a way to insert an element T
into a Stream<T>
?
ArrayList<Foo> foos = new ArrayList<>();
Foo foo = new Foo();
Stream<Foo> stream = Stream.concat(foos.stream(), Stream.of(foo));
Is there another way? basically a kind of foo.stream().add(foo)
... - of course add() doesn't exist. -
One approach is to use a terminal operation to collect the values of the stream to an ArrayList, and then simply use add(int index, E element) method. Keep in mind that this will give you the desired result but you will also lose the laziness of a Stream because you need to consume it before inserting a new element.
There are two methods to add elements to the list. add(E e ) : appends the element at the end of the list. Since List supports Generics , the type of elements that can be added is determined when the list is created. add(int index , E element ) : inserts the element at the given index .
Stream map() in Java with examples Stream map(Function mapper) returns a stream consisting of the results of applying the given function to the elements of this stream. Stream map(Function mapper) is an intermediate operation.
The stream(T[] array) method of Arrays class in Java, is used to get a Sequential Stream from the array passed as the parameter with its elements. It returns a sequential Stream with the elements of the array, passed as parameter, as its source.
No, there's no other way to add elements to the given stream in standard Java Stream API. Some third-party libraries including my StreamEx library provide additional convenient methods to do this:
Stream<Foo> stream = StreamEx.of(foos).append(foo);
Internally it uses the same concat
method.
Similar method is available in jOOL library:
Stream<Foo> stream = Seq.seq(foos).concat(foo);
Assuming that foos
don't exist. You can build a Stream
with the Stream.Builder
instead of an ArrayList
like this:
Stream.Builder<Integer> builder = Stream.builder();
for (int i = 0; i < 10; i++) {
builder.accept(i);
}
Stream<Integer> build = builder.add(50).build();
// ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With