-1

how can I calculate the variance with iterator?

public static double variance(final Iterator<Integer> array) {

}

-this method calculate the average

 private static double mean(final List<Integer> array) {
        return array.stream()
        .mapToInt(Integer::intValue)
        .average()
        .orElse(Double.NaN);
    }
Ella
  • 11
  • 1
  • 1
    Possible duplicate of [Simple statistics - Java packages for calculating mean, standard deviation, etc](https://stackoverflow.com/questions/1735870/simple-statistics-java-packages-for-calculating-mean-standard-deviation-etc) – Janus Varmarken Oct 07 '19 at 21:40
  • What is in the way of using the definition of variance? https://en.wikipedia.org/wiki/Variance – jrook Oct 07 '19 at 22:29
  • To calculate the variance without first writing everything to a list, use https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Welford's_online_algorithm – k314159 Jan 26 '22 at 11:56

1 Answers1

1

Based on this answer you can do:

public static double variance(final Iterator<Integer> iterator) {
  List<Integer> array = new ArrayList<>();
  iterator.forEachRemaining(array::add);
  double mean = mean(array);
  double temp = 0;
  for(double a :array)
    temp += (a-mean)*(a-mean);
  return temp/(array.size()-1);
}

But it is strange that in mean is used List. If this Iterator is not needed than it can be:

public static double variance(final List<Integer> array) {
  double mean = mean(array);
  double temp = 0;
  for(double a :array)
    temp += (a-mean)*(a-mean);
  return temp/(array.size()-1);
}

And with stream

public static double variance(final Iterator<Integer> iterator) {
  List<Integer> array = new ArrayList<>();
  iterator.forEachRemaining(array::add);
  double mean = mean(array);

  return array.stream()
          .map(a -> (a-mean)*(a-mean))
          .reduce(0d, Double::sum)/(array.size()-1);

}
lczapski
  • 4,026
  • 3
  • 16
  • 32