Как найти сумму всех элементов массива java

It depends. How many numbers are you adding? Testing many of the above suggestions:

import java.text.NumberFormat;
import java.util.Arrays;
import java.util.Locale;

public class Main {

    public static final NumberFormat FORMAT = NumberFormat.getInstance(Locale.US);

    public static long sumParallel(int[] array) {
        final long start = System.nanoTime();
        int sum = Arrays.stream(array).parallel().reduce(0,(a,b)->  a + b);
        final long end = System.nanoTime();
        System.out.println(sum);
        return  end - start;
    }

    public static long sumStream(int[] array) {
        final long start = System.nanoTime();
        int sum = Arrays.stream(array).reduce(0,(a,b)->  a + b);
        final long end = System.nanoTime();
        System.out.println(sum);
        return  end - start;
    }

    public static long sumLoop(int[] array) {
        final long start = System.nanoTime();
        int sum = 0;
        for (int v: array) {
            sum += v;
        }
        final long end = System.nanoTime();
        System.out.println(sum);
        return  end - start;
    }

    public static long sumArray(int[] array) {
        final long start = System.nanoTime();
        int sum = Arrays.stream(array) .sum();
        final long end = System.nanoTime();
        System.out.println(sum);
        return  end - start;
    }

    public static long sumStat(int[] array) {
        final long start = System.nanoTime();
        int sum = 0;
        final long end = System.nanoTime();
        System.out.println(sum);
        return  end - start;
    }


    public static void test(int[] nums) {
        System.out.println("------");
        System.out.println(FORMAT.format(nums.length) + " numbers");
        long p = sumParallel(nums);
        System.out.println("parallel " + FORMAT.format(p));
        long s = sumStream(nums);
        System.out.println("stream " +  FORMAT.format(s));
        long ar = sumArray(nums);
        System.out.println("arrays " +  FORMAT.format(ar));
        long lp = sumLoop(nums);
        System.out.println("loop " +  FORMAT.format(lp));

    }

    public static void testNumbers(int howmany) {
        int[] nums = new int[howmany];
        for (int i =0; i < nums.length;i++) {
            nums[i] = (i + 1)%100;
        }
        test(nums);
    }

    public static void main(String[] args) {
        testNumbers(3);
        testNumbers(300);
        testNumbers(3000);
        testNumbers(30000);
        testNumbers(300000);
        testNumbers(3000000);
        testNumbers(30000000);
        testNumbers(300000000);
    }
}

I found, using an 8 core, 16 G Ubuntu18 machine, the loop was fastest for smaller values and the parallel for larger. But of course it would depend on the hardware you’re running:

------
3 numbers
6
parallel 4,575,234
6
stream 209,849
6
arrays 251,173
6
loop 576
------
300 numbers
14850
parallel 671,428
14850
stream 73,469
14850
arrays 71,207
14850
loop 4,958
------
3,000 numbers
148500
parallel 393,112
148500
stream 306,240
148500
arrays 335,795
148500
loop 47,804
------
30,000 numbers
1485000
parallel 794,223
1485000
stream 1,046,927
1485000
arrays 366,400
1485000
loop 459,456
------
300,000 numbers
14850000
parallel 4,715,590
14850000
stream 1,369,509
14850000
arrays 1,296,287
14850000
loop 1,327,592
------
3,000,000 numbers
148500000
parallel 3,996,803
148500000
stream 13,426,933
148500000
arrays 13,228,364
148500000
loop 1,137,424
------
30,000,000 numbers
1485000000
parallel 32,894,414
1485000000
stream 131,924,691
1485000000
arrays 131,689,921
1485000000
loop 9,607,527
------
300,000,000 numbers
1965098112
parallel 338,552,816
1965098112
stream 1,318,649,742
1965098112
arrays 1,308,043,340
1965098112
loop 98,986,436

В этом посте мы обсудим, как получить сумму всех элементов массива в Java.

В Java не было встроенного метода для этой простой задачи, в отличие от многих других языков программирования, таких как std::accumulate в C++, array_sum() метод в PHP, Метод Enumerable.Sum (IEnumerable<Int32>) в .NET Frameworkи т. д. До Java 8 единственным решением было перебирать заданный массив с помощью цикла for-each и накапливать сумму всех элементов в переменной. Этот подход демонстрируется здесь.

 
С введением Java 8 Stream мы можем легко получить сумму всех элементов массива, используя Stream.sum() метод. Чтобы получить поток элементов массива, мы можем использовать функцию Arrays.stream() метод. Этот метод перегружен для массивов типа int, double и long. Также у него есть перегруженные версии, что позволяет получить сумму элементов между указанными индексами массива.

import java.util.Arrays;

class Main

{

    public static void main(String[] args)

    {

        int[] A = { 1, 2, 3, 4, 5 };

        int sum = Arrays.stream(A).sum();

        System.out.println(“The sum of all the array elements is “ + sum);

    }

}

Скачать  Выполнить код

 
Мы также можем назвать of() метод IntStream, DoubleStream, а также LongStream класс для массива int, double и long соответственно, чтобы получить поток элементов массива.

import java.util.stream.IntStream;

class Main

{

    public static void main(String[] args)

    {

        int[] A = { 1, 2, 3, 4, 5 };

        int sum = IntStream.of(A).sum();

        System.out.println(“The sum of all the array elements is “ + sum);

    }

}

Скачать  Выполнить код

 
Мы также можем использовать сокращение для выполнения операции сложения.

import java.util.Arrays;

class Main

{

    public static void main(String[] args)

    {

        int[] A = { 1, 2, 3, 4, 5 };

        int sum = Arrays.stream(A).reduce((x, y) -> x + y).getAsInt();

        // или использовать

        // int sum = Arrays.stream(A).reduce(0, (x, y) -> x + y);

        System.out.println(“The sum of all the array elements is “ + sum);

    }

}

Скачать  Выполнить код

 
Мы можем упростить приведенный выше код, используя ссылки на методы, как показано ниже:

import java.util.Arrays;

class Main

{

    public static void main(String[] args)

    {

        int[] A = { 1, 2, 3, 4, 5 };

        int sum = Arrays.stream(A).reduce(Integer::sum).getAsInt();

        System.out.println(“The sum of all the array elements is “ + sum);

    }

}

Скачать  Выполнить код

 
Наконец, мы можем использовать summaryStatistics() чтобы получить информацию об элементах этого потока, таких как минимальный/максимальный элемент, среднее значение и общая сумма. Он возвращается IntSummaryStatistics объект, который имеет getSum() метод получения суммы значений.

import java.util.Arrays;

class Main

{

    public static void main(String[] args)

    {

        int[] A = { 1, 2, 3, 4, 5 };

        long sum = Arrays.stream(A).summaryStatistics().getSum();

        System.out.println(“The sum of all the array elements is “ + sum);

    }

}

Скачать  Выполнить код

 
Это эквивалентно:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

import java.util.IntSummaryStatistics;

class Main

{

    public static void main(String[] args)

    {

        int[] A = { 1, 2, 3, 4, 5 };

        IntSummaryStatistics stat = new IntSummaryStatistics();

        for (int i : A) {

            stat.accept(i);

        }

        long sum = stat.getSum();

        System.out.println(“The sum of all the array elements is “ + sum);

    }

}

Скачать  Выполнить код

Это все о получении суммы всех элементов массива в Java.

Sum of array elements means the sum of all the elements(or digits) in the array. Array elements can be integers(int) or decimal numbers(float or double).
There are different methods to calculate sum of elements in an array in java and this post discusses them all.

Method 1: Using for loop
This is a traditional and most commonly used approach where the array is iterated using a for loop.
In each iteration, the current array element is added to a variable which holds the sum of array elements.
This variable is initialized to 0 before the start of loop. Example,

public class ArraySumCalculator {
 
   public static void main(String[] args) {
	int[] array = { 1, 34, 67, 23, -2, 18 };
        // variable to hold sum of array elements
	int sum = 0;
        // iterate using a for loop
	for (int loopCounter = 0; loopCounter &lt; array.length; loopCounter++) {
           // get current array element
	   int element = array[loopCounter];
           // add element to sum
	   sum += element;
	}
	System.out.println("Sum of array elements is: " + sum);
   }
}

sum += element is a short hand notation for sum = sum + element

Above program prints

Sum of array elements is: 141

for loop in this program can also be replaced with a for-each loop as shown below.

   for (int element: array) {
      sum += element;
   }

Method 2: Using Arrays.stream in java 8
This method uses stream concept introduced in java 8. Call stream method on java.util.Arrays class supplying it the array as argument. This method returns a stream of array elements.
Invoking sum method on this stream will provide the sum of elements in the array. Example,

import java.util.Arrays;
import java.util.stream.IntStream;
 
public class ArraySumCalculator {
 
   public static void main(String[] args) {
	int[] array = { 1, 34, 67, 23, -2, 18 };
        // get stream of elements
        IntStream stream = Arrays.stream(array);
        // add the elements in stream
	int sum = stream.sum();
	System.out.println("Sum of array elements is: " + sum);
   }
}

Note that calling stream method returns a java.util.stream.IntStream which is a stream of integer values. This is because the array supplied to stream method was an integer array.
If the array is of type double, then the stream will be of java.util.stream.DoubleStream
Above code can also be reduced to a single line as below.

int sum = Arrays.stream(array).sum();

Output of this program is the same as the previous one.

Method 3: Using IntStream in java 8
java 8 introduced java.util.stream.IntStream which is a sequence of elements. It has an of method taking an array as argument and returns a stream of the elements of array.
Calling sum method on the returned stream provides the sum of array elements. Example,

import java.util.stream.IntStream;
 
public class ArraySumCalculator {
 
   public static void main(String[] args) {
	int[] array = { 1, 34, 67, 23, -2, 18 };
        // get stream of elements
        IntStream stream = IntStream.of(array);
        // add the elements in stream
	int sum = stream.sum();
	System.out.println("Sum of array elements is: " + sum);
   }
}

Above code can be reduced to a one-liner as below.

int sum = IntStream.of(array).sum();

Method 4: Using reduction operation on stream
This method also uses a stream to find the sum of array elements. Once a stream is obtained, you can apply reduction on it.
From javadocs,

reduction operation takes a sequence of input elements and combines them into a single summary result by repeated application of a combining operation, such as finding the sum or maximum of a set of numbers, or accumulating elements into a list.

java.util.stream.IntStream has a reduce method which takes 2 arguments. First is the identity element for the required operation. For addition operation, identity is 0.

Second argument is an argument of type java.util.function.InitBinaryOperator which is a functional interface having a method applyAsInt that applies an operation to the supplied operands.
Implementation to this method can be provided by using a Lambda expression. Example,

import java.util.stream.IntStream;
 
public class ArraySumCalculator {
 
   public static void main(String[] args) {
	int[] array = { 1, 34, 67, 23, -2, 18 };
        // get stream of elements
        IntStream stream = IntStream.of(array);
        // add the elements in stream using reduction
	int sum = stream.reduce(0,(element1, element2)-&gt; element1 + element2);
	System.out.println("Sum of array elements is: " + sum);
   }
}

Note the arguments to reduce method.
First is 0, which is the identity for addition.
Second is a lambda expression which says “apply addition operation on the supplied elements”.
This method will iterate over all the array elements and perform addition of those elements.
Above method can be reduced to a one-liner as.

int sum = IntStream.of(array).reduce(0,(element1, element2)-&gt; element1+element2);

Method 5: Using Apache Math library
All the above methods are applicable to an array of integers. They can also be modified if the array is of decimal elements.
But if you specifically have an array of type double, then this method can be used to calculate the sum of its elements. Example,

import org.apache.commons.math3.stat.StatUtils;
 
public class ArraySumCalculator {
 
   public static void main(String[] args) {
	double[] array = { 1, 34, 67, 23, -2, 18 };
	int sum = (int)StatUtils.sum(array);
	System.out.println("Sum of array elements is: " + sum);
   }
}

sum method from class org.apache.commons.math3.stat.StatUtils of Apache Math library takes a double array as argument and returns the sum of its elements.
This method only takes an array of type double as argument.
Note that we have explicitly casted the sum to an int. This is because the return type of sum is double.
Casting is not required if you want the sum in decimal format.
To include Apache Math library to your project, add the following dependency as per the build tool.

<!- – Maven – ->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-math3</artifactId>
<version>3.6.1</version>
</dependency>

<!- – Gradle – ->
compile group: ‘org.apache.commons’, name: ‘commons-math3’, version: ‘3.6.1’

Hope this article helped you in calculating the sum of all elements of an array.

  1. Find the Sum of an Array by Using a for Loop in Java
  2. Find the Sum of an Array by Using the Stream Method in Java
  3. Find the Sum of an Array by Using the reduce Method in Java
  4. Find the Sum of an Array by Using the sum Method in Java
  5. Find the Sum of an Array by Using the IntStream Interface in Java
  6. Find the Sum of an Array by Using a Compact for Loop in Java

Get the Sum of an Array in Java

This tutorial introduces how to find the sum of an array in Java also lists some example codes to understand the topic.

An array is defined as a collection of similar types of elements in Java. In this article, we’ll find the sum of array elements by using some built-in methods and custom codes.

Performing this operation is very common during programming. Unfortunately, Java does not provide any specific method to get the sum of an array. So, we will use some tricks to solve this issue!

Find the Sum of an Array by Using a for Loop in Java

In this example, we used a loop to traverse each array element and get thir sum parallel. This method has a simple code that requires a single loop to get the sum. Here’s the example program:

public class SimpleTesting{
    public static void main(String[] args) {
        int arr[] = new int[] {12,34,45,21,33,4};
        int sum = 0;
        for (int i = 0; i < arr.length; i++) {
            sum+=arr[i];
        }
        System.out.println("Array Sum = "+sum);
        
    }
}

Output:

Find the Sum of an Array by Using the Stream Method in Java

In this example, we used the stream() method of the Arrays class and the parallel() method to get the sum of the array elements. We passed the lambda expression to the reduce() method that actually does the sum operation. See the example below:

import java.util.Arrays;
public class SimpleTesting{
    public static void main(String[] args) {
        int arr[] = new int[] {12,34,45,21,33,4};
        int sum = Arrays.stream(arr).parallel().reduce(0,(a,b)->  a + b);
        System.out.println("Array Sum = "+sum);
        
    }
}

Output:

Find the Sum of an Array by Using the reduce Method in Java

In this example, we used the reduced() method directly with the stream of arrays and get the sum of the elements. Here’s how to do it:

import java.util.Arrays;
public class SimpleTesting{
    public static void main(String[] args) {
        int arr[] = new int[] {12,34,45,21,33,4};
        int sum = Arrays.stream(arr).reduce(0,(a,b)->  a + b);
        System.out.println("Array Sum = "+sum);

    }
}

Output:

Find the Sum of an Array by Using the sum Method in Java

Java provides the sum() method in the Stream API to get a sum of stream sequences. Here, we passed an array to the stream and got its sum by using the sum() method. See the example below:

import java.util.Arrays;
public class SimpleTesting{
    public static void main(String[] args) {
        int arr[] = new int[] {12,34,45,21,33,4};
        int sum = Arrays.stream(arr).sum();
        System.out.println("Array Sum = "+sum);
    }
}

Output:

Find the Sum of an Array by Using the IntStream Interface in Java

This method is another solution where you can use the Intsream interface to create a stream of array elements and utilize the sum() method to get the sum in a straightforward, single-line solution. Follow the sample code here:

import java.util.stream.IntStream;
public class SimpleTesting{
    public static void main(String[] args) {
        int arr[] = new int[] {12,34,45,21,33,4};
        int sum = IntStream.of(arr).sum();
        System.out.println("Array Sum = "+sum);
    }
}

Output:

Find the Sum of an Array by Using a Compact for Loop in Java

In this example, we used a for loop to get the sum of array elements with an additional unique process. Here, rather than creating a loop body, we just bind up into the loop signature part. We can call it a compact loop solution. You can try it if you’re not afraid of a messy code block.

public class SimpleTesting{
    public static void main(String[] args) {
        int arr[] = new int[] {12,34,45,21,33,4};
        int sum,i;
        for(sum= 0, i= arr.length - 1; 0 <= i; sum+= arr[i--]);
        System.out.println("Array Sum = "+sum);
    }
}

Output:

Every now and then, I need to do some basic stuff in Java and I wonder what is the best way to this. This happened to me a few days ago! I needed to simply get the sum of a List of numbers and I found out there are a number of ways — pun intended — to do this.

The old-fashioned approach

We can create a simple loop to do this. I am using Java 11 so, forgive me if you are using, for example, Java 8,  and the List.of and var does not work in your case. Nonetheless, I believe you’ll still get the point.

var listOfNumbers = List.of(1,2,3,4,5,6,7,8,9,10);

var sum = 0;
for (int i = 0; i < listOfNumbers.size() ; i++) {
    sum += listOfNumbers.get(i);
}

Obviously, since Java 5, we have enhancements for loops so, I can rewrite the same code like this.

var listOfNumbers = List.of(1,2,3,4,5,6,7,8,9,10);

var sum = 0;
for (int number : listOfNumbers) {
    sum += number;
}

The difference is subtle. However, it is already more expressive as it says something like “of each number coming from listOfNumbers I want to do the following …”.

The Java Stream approach

People who know me, know that I was brainwashed, during my university days, with programming in Haskell. This means I have a lot of love for pure functional programming. Not that Java can handle that ?, but the expressiveness of functional programming is somewhat available using the stream API.

With the stream API in Java, we can execute the MapReduce programming model. For the issue I am trying to solve here, I do not need to map as the numbers will stay as they are. I do, however, have to reduce the List into a single number, the sum.

Collect

In probably 99% of the cases, we use the collect function with the standard toList() collector to reduce our stream back into a List.Similar to this:

       var time2ToList = listOfNumbers.stream()
                .map(i -> i * 2)
                .collect(Collectors.toList());

However, there is more to life than collecting a stream back into a List. Browsing the Collectors library you can find functions like summingInt(), summingDouble() and summingLong().You can use these functions to collect (or reduce) the List into the sum.

The summmingInt function does require a function that turns the input you have into an int. In this case, I can simply use “identity function”. The functioni -> i will be sufficient.

        var listOfNumbers = List.of(1,2,3,4,5,6,7,8,9,10);
        var sum = listOfNumbers.stream()
                    .collect(Collectors.summingInt(i -> i));

This identity function might look silly so, you can use Integer.intValue() instead.

       var listOfNumbers = List.of(1,2,3,4,5,6,7,8,9,10);
       var sum = listOfNumbers.stream()
                .collect(Collectors.summingInt(Integer::intValue));

When I do this, my IDE—IntelliJ IDEA in my case—advises me to refactor this and use the mapToInt() function like seen below:

       var listOfNumbers = List.of(1,2,3,4,5,6,7,8,9,10);
       var sum = listOfNumbers.stream()
                .mapToInt(Integer::intValue).sum();

Technically what we do here is mapping every item to an int, what it already is ¯(ツ)/¯  right, and reduce it with the sum() function.

It gets more clear if you look at the inferred types. You simply cannot have a List of primitives. So, the List is a list of Integer (the Object). This means that every item in the list needs to get back to the primitive int to make the sum() possible. The previous example with the identity function in the collector works because of Java unboxing.

If you prefer using primitive Lists in Java, I suggest taking a look at the Eclipse Collections library.

Reduce

Reduction in Java is achieved by a couple of function in the stream API.In addition to collect(), there is also the obviously-named function reduce().

       var listOfNumbers = List.of(1,2,3,4,5,6,7,8,9,10);
       var sum = listOfNumbers.stream()
                .reduce(0 , (num1, num2) -> num1 + num2);

The reduce function in this case takes a starting point and BiFunction lambda expression. The BiFunction is applied to the starting point and the first number,he result of the function is applied to the second number, and so on.

The code above does something like this:0 + 11 + 23 + 36 + 4etc …

Now, you can omit the starting point 0. However, the reduce function will return an Optional in this case as the List it tries to reduce might be empty.

Conclusion

As you can see, there are multiple ways to solve this problem. Without any doubt, people will come up with even more exotic ways to solve this. My personal favorite is the reduce() option. For me, this is the most expressive and pure solution in Java. I simply want to reduce a list to a single number and don’t need to care of the transformations from boxed types to primitives. Furthermore, I can reuse this approach when I need to reduce a List of other types by writing a reduction lambda function that fits my needs.

Добавить комментарий