[英]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: 我一直在努力的是:
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; Iterable
和几乎( 1 ) Iterable
操作工具; 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)
: 您可以使用
Collections
的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).
请注意,
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.