java - Getting two different outputs from a Stream -


i testing out new stream api in java-8 , want check outcome of 10000 random coinflips. far 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());     } 

but throws exception:

 java.lang.illegalstateexception: stream has been operated upon or closed 

i understand why happenning how can print count heads , tails if can use stream once?

this first solution relying on fact counting number of heads , tails of 10 000 coinflips follows binomial law.

for particular use case, can use 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 can use collect operation create map map each possible result number of occurences in 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 last solution works bounds give random integers want generate.

example:

intstream randomstream = r.ints(10000,0, 5); .... map => {0=1991, 1=1961, 2=2048, 3=1985, 4=2015} 

Comments

Popular posts from this blog

how to proxy from https to http with lighttpd -

android - Automated my builds -

python - Flask migration error -