collections - Java Lambda re-use Stream -



collections - Java Lambda re-use Stream -

i wanted seek out of functionality of lambdas , wanted write filter arraylist , utilize methods of intstream calculate average , maximum of arraylist of numbers

my first thought filter arraylist, save stream , utilize methods calculate:

arraylist<integer> arr = new arraylist<>(); arr.add(5); arr.add(7); arr.add(11); intstream s = arr.stream().filter(i -> < 10).maptoint(i -> (int)i); int maxbelowten = s.max().getasint(); double avgbelowten = s.average().getasdouble(); system.out.println("maximum below ten: " + maxbelowten); system.out.println("average below ten: " + avgbelowten);

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

with information, brought work of course, opening 2 streams , filtering twice

int maxbelowten = arr.stream().filter(i -> < 10).maptoint(i -> (int) i).max().getasint(); double avgbelowten = arr.stream().filter(i -> < 10).maptoint(i -> (int) i).average().getasdouble();

but question performance. isn't pretty slow, if have filter , map stream twice. why can't operate more 1 time on stream, fail understand why implemented way. wouldn't possible leave stream open after operation, because every operator method returns new stream or single value.

what reason this, or using wrong?

if did old way, using loop, compute max element , average using single loop. need same thing here. , fortunately, stream api can :

intstream s = arr.stream().maptoint(i -> integer::intvalue).filter(i < 10); intsummarystatistics stats = s.summarystatistics(); double average = stats.getaverage(); int max = stats.getmax();

reading javadoc of intsummarystatistics should help understand how implement such operation yourself.

java collections lambda java-8 java-stream

Comments

Popular posts from this blog

php - Android app custom user registration and login with cookie using facebook sdk -

django - Access session in user model .save() -

php - .htaccess Multiple Rewrite Rules / Prioritizing -