Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate stream of Boolean

How do you create stream of Boolean.FALSE, say, length of 100?

What I've struggled with is:

  1. Originally I've intended to create an array of Boolean.FALSE. But new Boolean[100] returns an array of NULL. So reasonably I considered to use stream API as a convenient Iterable and almost (1) Iterable manipulation tool;
  2. There is no Boolean no-params constructor (2), hence I can't use Stream.generate(), since it accepts Supplier<T> (3).

What I found is Stream.iterate(Boolean.FALSE, bool -> Boolean.FALSE).limit(100); gives what I want, but it doesn't seem to be quite elegant solution, IMHO.

One more option, I found (4) is IntStream.range(0, 100).mapToObj(idx -> Boolean.FALSE);, which seems to me even more strange.

Despite these options don't violate pipeline conception of a stream API, are there any more concise ways to create stream of Boolean.FALSE?

like image 477
Eugene Mamaev Avatar asked Dec 02 '22 12:12

Eugene Mamaev


1 Answers

Even though Boolean has no no-arg constructor, you can still use Stream.generate using a lambda:

Stream.generate(() -> Boolean.FALSE).limit(100)

This also has the advantage (compared to using a constructor) that those will be the same Boolean instances, and not 100 different but equal ones.

like image 141
tobias_k Avatar answered Dec 14 '22 23:12

tobias_k