Find Sum and Average in a Java Array – 查找Java数组中的总和和平均数

最后修改: 2018年 4月 2日

中文/混合/英文(键盘快捷键:t)

1. Introduction

1.绪论

In this quick tutorial, we’ll cover how we can calculate sum & average in an array using both Java standard loops and the Stream API.

在这个快速教程中,我们将介绍如何使用Java标准循环和Stream API计算数组中的和与平均。

2. Find Sum of Array Elements

2.寻找数组元素的总和

2.1. Sum Using a For Loop

2.1.使用For循环进行求和

In order to find the sum of all elements in an array, we can simply iterate the array and add each element to a sum accumulating variable.

为了找到一个数组中所有元素的总和,我们可以简单地迭代该数组,并将每个元素添加到一个sum累积变量。

This very simply starts with a sum of 0 and add each item in the array as we go:

这很简单,从sum的0开始,然后在数组中加入每一项。

public static int findSumWithoutUsingStream(int[] array) {
    int sum = 0;
    for (int value : array) {
        sum += value;
    }
    return sum;
}

2.2. Sum With the Java Stream API

2.2.使用Java流API的总结</b

We can use the Stream API for achieving the same result:

我们可以使用流API来实现同样的结果:

public static int findSumUsingStream(int[] array) {
    return Arrays.stream(array).sum();
}

It’s important to know that the sum() method only supports primitive type streams.

要知道,sum()方法只支持primitive type streams

If we want to use a stream on a boxed Integer value, we must first convert the stream into IntStream using the mapToInt method.

如果我们想在一个盒装的Integer值上使用流,我们必须首先使用mapToInt方法将流转换成IntStream

After that, we can apply the sum() method to our newly converted IntStream:

之后,我们可以将sum()方法应用于我们新转换的IntStream

public static int findSumUsingStream(Integer[] array) {
    return Arrays.stream(array)
      .mapToInt(Integer::intValue)
      .sum();
}

You can read a lot more about the Stream API here.

你可以在这里阅读更多关于Stream API的信息

3. Find Average in a Java Array

3.寻找Java数组中的平均数

3.1. Average Without the Stream API

3.1.不使用流API的平均数</b

Once we know how to calculate the sum of array elements, finding average is pretty easy – as Average = Sum of Elements / Number of Elements:

一旦我们知道如何计算数组元素的总和,寻找平均数就非常容易了–因为平均数=元素之和/元素数

public static double findAverageWithoutUsingStream(int[] array) {
    int sum = findSumWithoutUsingStream(array);
    return (double) sum / array.length;
}

Notes:

注释

  1. Dividing an int by another int returns an int result. To get an accurate average, we first cast sum to double.
  2. Java Array has a length field which stores the number of elements in the array.

3.2. Average Using the Java Stream API

3.2.使用Java流API的平均值</b

public static double findAverageUsingStream(int[] array) {
    return Arrays.stream(array).average().orElse(Double.NaN);
}

IntStream.average() returns an OptionalDouble which may not contain a value and which needs a special handling.

IntStream.average()返回一个OptionalDouble,它可能不包含一个值,需要特殊处理。

Read more about Optionals in this article and about the OptionalDouble class in the Java 8 Documentation.

这篇文章中阅读更多关于Optional的内容,在Java 8 文档中阅读关于OptionalDouble类的内容。

4. Conclusion

4.总结

In this article, we explored how to find sum/average of int array elements.

在这篇文章中,我们探讨了如何寻找int数组元素的总和/平均数。

As always, the code is available over on Github.

像往常一样,代码可以在Github上获得