Java – get two different outputs from stream
•
Java
I'm testing the new stream API in java-8 and want to check the results of 10000 random coinplips So far, I have:
public static void main(String[] args) { Random r = new Random(); IntStream randomStream = r.ints(10000,2); System.out.println("Heads: " + randomStream.filter(x -> x==1).count()); System.out.println("Tails: " + randomStream.filter(x -> x==0).count()); }
But this threw an exception:
java.lang.IllegalStateException: stream has already been operated upon or closed
I understand why this happens, but if I can only use the stream once, how can I print the head and tail counts?
Solution
The first solution relies on the fact that the number of heads and tails of 10000 coins is calculated according to the binomial law
For this particular use case, you can use @ L_ 301_ 2 @ method
Random r = new Random(); IntStream randomStream = r.ints(10000,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 that maps each possible result to its number of occurrences 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 applies to any boundary you provide for the random integer to be generated
Example:
IntStream randomStream = r.ints(10000,5); .... map => {0=1991,1=1961,2=2048,3=1985,4=2015}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码