I have an array of primitives, which can contain Nan values. How do I calculate an aggregate of it? Like, org.apache.commons.math3.stat.descriptive.moment.Mean gives Nan as an output.
Of course, I can code this by hand, but maybe an elegant and efficient solution exists already?
1 Answer
If you use the stream API, you can use the filter function to remove NaN and other "irregular" values when you compute the statistics.
double[] array = {1, Double.NaN, 3};
DoubleSummaryStatistics statistics = Arrays.stream(array).filter(Double::isFinite).summaryStatistics();
double average = statistics.getAverage(); // 2.0
double sum = statistics.getSum(); // 4.0
3 Comments
Alexey Mints
Thanks a lot! I'll give it a try.
Alexey Mints
Btw, how numerically efficient is stream API? I have to call this function many (millions) of times, so it is significant not to slow things down...
Joni
Try and see. If it turns out to be a bottle neck later on it's easy to replace with something else