Insert item into stream

Is there a way to insert a T element 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 () does not exist. -

+6
source share
2 answers

No, there is no other way to add elements to this stream in the standard Java Stream API. Some third-party libraries, including the StreamEx library, provide additional convenient methods for this:

 Stream<Foo> stream = StreamEx.of(foos).append(foo); 

Inside, it uses the same concat method.

A similar method is available in jOOL :

 Stream<Foo> stream = Seq.seq(foos).concat(foo); 
+7
source

Assuming foos doesn't exist. You can build Stream with Stream.Builder instead of ArrayList as follows:

 Stream.Builder<Integer> builder = Stream.builder(); for (int i = 0; i < 10; i++) { builder.accept(i); } Stream<Integer> build = builder.add(50).build(); // ... 
+1
source

All Articles