简体   繁体   中英

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 ?

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.

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

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

Note that the List returned by nCopies is tiny (it contains a single reference to the data object). , so it doesn't require more storage compared to the Stream.generate().limit() solution, regardless of the required size.

of course you could create the stream directly

Stream.Builder<Boolean> builder = Stream.builder();
for( int i = 0; i < 100; i++ )
  builder.add( false );
Stream<Boolean> stream = builder.build();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM