Create boolean stream

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

What I struggled with:

  • I originally intended to create an array Boolean.FALSE. But it new Boolean[100]returns an array NULL. Therefore, I reasonably considered using the stream API as a convenient tool Iterableand almost ( 1 ) Iterable;
  • There is no no Booleanno-params constructor ( 2 ), so I can’t use Stream.generate(), since it accepts Supplier<T>( 3 ).

What I found Stream.iterate(Boolean.FALSE, bool -> Boolean.FALSE).limit(100);gives what I want, but it does not seem like a pretty elegant solution, IMHO.

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

Despite the fact that these parameters do not violate the concept of the stream API pipeline, are there more concise ways to create a stream Boolean.FALSE?

+4
source share
2 answers

Even if you Booleandon't have a no-arg constructor, you can still use Stream.generateusing lambda:

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

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

+8
source

You can use Collections static <T> List<T> nCopies(int n, T o):

Collections.nCopies (100, Boolean.FALSE).stream()...

Please note that List, returned nCopies, tiny (it contains a single reference to the data object).therefore it does not require more storage compared to the solution Stream.generate().limit(), regardless of the size required.

+7
source

Source: https://habr.com/ru/post/1687543/


All Articles