Jack Avante
Jack Avante

Reputation: 1595

How to terminate a Java stream without the use of a terminating statement?

I've been playing around with streams and then I noticed that when I do the following, it won't produce an output into the console:

String[] is = {"Hello", "World", "My", "Name", "Is", "Jacky"};
Arrays.stream(is).peek(s -> System.out.println(s));

I figure this is because peek() is a non-terminating stream method, and forEach() should be used instead of peek() to terminate the stream and produce the results:

Arrays.stream(is).forEach(s -> System.out.println(s));

Is there however a way to terminate a stream 'early', using perhaps a custom terminating method (functional interface) that wouldn't do anything except for terminating the stream?.. Is there a proper way to do this with what is already present in Java?

I understand I could do something like this:

Arrays.stream(is).peek(s -> System.out.println(s)).forEach(s -> {});

But that feels wasteful.

Upvotes: 2

Views: 2062

Answers (1)

Eugene
Eugene

Reputation: 120848

There is no such thing.

There have been discussion around such functionality, for example here, where you can read that this will not happen and why.

You best option is forEach(x -> {}) or you can create such a dummy consumer yourself and use it everywhere needed:

static class Dummies {
     static <T> Consumer<T> getConsumer() {
         return x -> {};
     }
}

Upvotes: 2

Related Questions