Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert element into stream

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

like image 318
Johnny Willer Avatar asked Oct 04 '15 06:10

Johnny Willer


People also ask

How do you add an element to a stream?

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.

How do I add elements to an existing list in Java?

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 .

What does stream () map do?

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.

Can we use stream with Array?

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.


2 Answers

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);
like image 70
Tagir Valeev Avatar answered Sep 20 '22 12:09

Tagir Valeev


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();
// ...
like image 21
Flown Avatar answered Sep 20 '22 12:09

Flown