从Stream获取两个不同的输出 [英] Getting two different outputs from a Stream
问题描述
我正在测试新的 Stream
API ,并希望检查10000随机coinflips的结果。到目前为止我有:
I am testing out the new Stream
API in java-8 and want to check the outcome of 10000 random coinflips. So far I have:
public static void main(String[] args) {
Random r = new Random();
IntStream randomStream = r.ints(10000,0, 2);
System.out.println("Heads: " + randomStream.filter(x -> x==1).count());
System.out.println("Tails: " + randomStream.filter(x -> x==0).count());
}
但这会引发异常:
java.lang.IllegalStateException: stream has already been operated upon or closed
我理解为什么会发生这种情况,但如果我只能使用一次流,我如何打印头尾的计数?
I understand why this is happenning but how can i print the count for heads and tails if I can only use the stream once?
推荐答案
这第一个解决方案依赖于计算10 000个硬币翻转的头尾数量遵循二项式定律的事实。
This first solution is relying on the fact that counting the number of heads and tails of 10 000 coinflips follows a binomial law.
为此特定用例,您可以使用 summaryStatistics
方法。
For this particular use case, you can use the summaryStatistics
method.
Random r = new Random();
IntStream randomStream = r.ints(10000,0, 2);
IntSummaryStatistics stats = randomStream.summaryStatistics();
System.out.println("Heads: "+ stats.getSum());
System.out.println("Tails: "+(stats.getCount()-stats.getSum()));
否则你可以使用
收集
操作来创建一个地图,该地图将每个可能的结果与其在流中出现的次数进行映射。
Otherwise you can use the
collect
operation to create a map which will map each possible result with its number of occurences in the stream.
Map<Integer, Integer> map = randomStream
.collect(HashMap::new,
(m, key) -> m.merge(key, 1, Integer::sum),
Map::putAll);
System.out.println(map); //{0=4976, 1=5024}
最后一个解决方案的优势在于它的工作原理对于你想要生成的随机整数给出的任何边界。
The advantage of the last solution is that this works for any bounds you give for the random integers you want to generate.
示例:
IntStream randomStream = r.ints(10000,0, 5);
....
map => {0=1991, 1=1961, 2=2048, 3=1985, 4=2015}
这篇关于从Stream获取两个不同的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!