create empty stream and add elements to it

nim*_*o23 0 java java-stream

I want to have a stream where I can put elements after creation:

Stream<Task> all2 = Stream.of();
Run Code Online (Sandbox Code Playgroud)

Because the return type of the method is also a Stream and I want to avoid the extra cost by using a list and the need for return list.stream():

Stream<Task> getAll(){
    Stream<Task> all2 = Stream.of();

    all2.add(item1);
    ..

    return all2
}
Run Code Online (Sandbox Code Playgroud)

But how can I add elements to all2 for further processing?

Is this the only way to do this:

Stream<Task> all2 = Stream.of();
all2 = Stream.concat(all2, Stream.of(new Task("hello")));
...
all2 = Stream.concat(all2, Stream.of(new Task("hello_1000000")));
Run Code Online (Sandbox Code Playgroud)

Is this really cheaper than using a list and add elements to it?

List<Task> all = new ArrayList<>();
all.add(new Task("hello");
...
all.add(new Task("hello_1000000");
return all.stream();
Run Code Online (Sandbox Code Playgroud)

Fur*_*ish 6

Reading the comments you probably need a Stream of infinitely generated elements. Stream::generate does that:

import java.util.Scanner;
import java.util.function.Predicate;
import java.util.stream.Stream;

public class Main {
    public static void main(String[] args) {

        getStream()
                .forEach(System.out::println);

    }

    static String getUserInput(Scanner scanner) {
        return scanner.nextLine();
    }

    static Stream<String> getStream() {
        Scanner sc = new Scanner(System.in);

        return Stream.generate(() -> getUserInput(sc)).takeWhile(Predicate.not(String::isEmpty));
    }
}
Run Code Online (Sandbox Code Playgroud)

With this approach you have a Stream<String>, which will wait for the user to input elements (inifitely, or up to the first error or empty() String) and apply the stream operations to every element (in this case, forEach - as shown in main()).


Joh*_*uhn 5

看起来像是Stream.Builder的完美案例

Stream<Task> getAll(){
    Stream.Builder<Task> all2 = Stream.builder();

    all2.add(item1);
    ..

    return all2.build();
}
Run Code Online (Sandbox Code Playgroud)