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

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:

Как найти сумму элементов массива? Программа на Java

Сегодня мы рассмотрим программу для подсчета суммы элементов массива на Java. Рассмотрим 2 примера программы: первая будет подсчитывать сумму элементов уже инициализированного массива с определенным количеством элементов, а другая программа будет считать сумму элементов массива, введенного пользователем. Эта статья является частью раздела для начинающих Java программистов.

Сумма элементов уже инициализированного массива на Java

package ua.com.prologistic;

public class SumOfArray{

   public static void main(String args[]){

      int[] array = {10, 30, 20, 50, 40, 10};

      int sum = 0;

      // цикл для обхода каждого элемента массива

      for( int num : array) {

          // суммирование каждого элемента массива

          sum = sum + num;

      }

      System.out.println(“Сумма элементов массива равна: “ + sum);

   }

}

Результат выполнения этой программы:

Сумма элементов массива равна: 160

Сумма элементов введенного пользователем массива на Java

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

package ua.com.prologistic;

import java.util.Scanner;

/*

  Программа просит пользователя ввести 10 элементов в консоль.

  Эти элементы сохранятся в массиве и потом в консоль

  выведется сумма всех элементов

*/

public class SumDemo{

   public static void main(String args[]){

      Scanner scanner = new Scanner(System.in);

      int[] array = new int[10];

      int sum = 0;

      System.out.println(“Введите число:”);

      for (int i=0; i < 10; i++)

      {

          // считываем введенный пользователем элемент в массив

       array[i] = scanner.nextInt();

      }

      // проходим по всем элементов массива и суммируем каждое число

      for( int num : array) {

          sum = sum+num;

      }

      System.out.println(“Сумма элементов массива равна: “ + sum);

   }

}

Результат выполнения второй программы суммирования элементов массива на Java:

Введите число:

4

3

2

1

10

9

8

5

6

7

Сумма элементов массива равна: 55

Следите за обновлениями раздела для начинающих Java программистов.

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