i wanted to try out some of the functionality of lambdas and wanted to write filter an ArrayList and use the methods of IntStream to calculate the average and maximum of an ArrayList of numbers
My first thought was to just filter the ArrayList, save the stream and then use the methods to calculate:
ArrayList<Integer> arr = new ArrayList<>();
arr.add(5);
arr.add(7);
arr.add(11);
IntStream s = arr.stream().filter(i -> 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, this throws an java.lang.IllegalStateException: stream has already been operated upon or closed
With this information, i brought it to work of course, by opening two streams and filtering twice
int maxBelowTen = arr.stream().filter(i -> i < 10).mapToInt(i -> (int) i).max().getAsInt();
double avgBelowTen = arr.stream().filter(i -> i < 10).mapToInt(i -> (int) i).average().getAsDouble();
But my question now is about performance. Isn't that pretty slow, if i have to filter and map the stream twice. Why can't I operate more than once on a stream, i fail to understand why they implemented it this way. Wouldn't it be possible to leave a stream open after an operation, because every operator method returns a new stream or a single value.
What is the reason for this, or am I just using it wrong?