Bohemian
Bohemian

Reputation: 425033

Does the JDK provide a dummy consumer?

I have a need in a block of code to consume 'n' items from a stream then finish, in essence:

 public static <T> void eat(Stream<T> stream, int n) 
     // consume n items of the stream (and throw them away)
 }

In my situation, I can't change the signature to return Stream<T> and simply return stream.skip(n); I have to actually throw away some elements from the stream (not simple logic) - to be ready for a down stream consumer which doesn't need to know how, or even that, this has happened.

The simplest way to do this is to use limit(n), but I have to call a stream terminating method to activate the stream, so in essence I have:

public static <T> void skip(Stream<T> stream, int n) {
    stream.limit(n).forEach(t -> {});
}

Note: This code is a gross over simplification of the actual code and is for illustrative purposes only. Actually, limit won't work because there is logic around what/how to consume elements. Think of it like consuming "header" elements from a stream, then having a consumer consume the "body" elements.

This question is about the "do nothing" lambda t -> {}.

Is there a "do nothing" consumer somewhere in the JDK, like the "do nothing" function Function.identity()?

Upvotes: 54

Views: 23174

Answers (3)

Bohemian
Bohemian

Reputation: 425033

Yes. Well, more or less yes...

Since a Function is also a Consumer, you can use Function.identity() as a "do nothing" Consumer.

However, the compiler needs a little help to make the leap:

someStream.forEach(identity()::apply);

Upvotes: 6

Introducing the dummy (empty) consumer was considered in the scope of the ticket:

According to the ticket, it was decided not to introduce it.

Therefore, there is no dummy (empty) consumer in the JDK.

Upvotes: 5

Tagir Valeev
Tagir Valeev

Reputation: 100209

No, JDK does not provide dummy consumer as well as other predefined functions like dummy runnable, always-true predicate or supplier which always returns zero. Just write t -> {}, it's anyways shorter than calling any possible ready method which will do the same.

Upvotes: 58

Related Questions