简体   繁体   English

生成布尔流

[英]Generate stream of Boolean

How do you create stream of Boolean.FALSE , say, length of 100? 如何创建长度为100的Boolean.FALSE流?

What I've struggled with is: 我一直在努力的是:

  1. Originally I've intended to create an array of Boolean.FALSE . 最初,我打算创建一个Boolean.FALSE数组。 But new Boolean[100] returns an array of NULL . 但是new Boolean[100]返回一个NULL数组。 So reasonably I considered to use stream API as a convenient Iterable and almost ( 1 ) Iterable manipulation tool; 因此,我合理地考虑将流API用作方便的Iterable和几乎( 1Iterable操作工具;
  2. There is no Boolean no-params constructor ( 2 ), hence I can't use Stream.generate() , since it accepts Supplier<T> ( 3 ). 没有Boolean无参数构造函数( 2 ),因此我不能使用Stream.generate() ,因为它接受Supplier<T>3 )。

What I found is Stream.iterate(Boolean.FALSE, bool -> Boolean.FALSE).limit(100); 我发现的是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); 我发现了另外一个选择( 4 )是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 ? 尽管这些选项没有违反流API的管道概念,但是还有其他更简洁的方法来创建Boolean.FALSE流吗?

Even though Boolean has no no-arg constructor, you can still use Stream.generate using a lambda: 即使Boolean没有no-arg构造函数,您仍然可以使用lambda来使用Stream.generate

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. 与使用构造函数相比,这还有一个优势,即它们将是相同的 Boolean实例,而不是100个不同但相等的实例。

You can use Collections 's static <T> List<T> nCopies(int n, T o) : 您可以使用Collectionsstatic <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). 请注意, nCopies返回的List 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. ,因此与Stream.generate().limit()解决方案相比,它不需要更多的存储空间,而无需考虑大小。

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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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