- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to Find Sum of Matrix Elements in Java?
In Java, Array is an object. It is a non-primitive data type which stores values of similar data type. The matrix in java is nothing but a multi-dimensional array which represents multiple rows and columns.
Here we have given a matrix which contains set of elements and as per the problem statement we have to find out the sum of all the elements present inside the matrix.
Let’s deep dive into this article, to know how it can be done by using Java programming language.
To show you some instances
Instance-1
Given matrix =
21 22 23 24 25 26 27 28 29
Sum of elements of the above matrix = 315
Instance-2
Given matrix =
121 222 243 432 124 245 256 657 237 258 229 345 176 453 756 343
Sum of elements of the above matrix = 4194
Instance-3
Given matrix =
1 2 3 4 5 6 7 8 9
Sum of elements of the above matrix = 45
Algorithm
Algorithm-1
Step-1 − A 2D matrix is declared.
Step-2 − The user defined method is called to find the sum of all elements in the matrix.
Step-3 − The method uses two nested loops to iterate over each element in the matrix and add the value of the current element to a running total.
Step-4 − The method returns the sum of all elements in the matrix.
Algorithm-2
Step-1 − A 2D matrix is declared.
Step-2 − The user defined method is called to find the sum of all elements in the matrix.
Step-3 − The method uses Arrays.stream to convert the 2D matrix into a 1D stream of elements and forEach to add the value of each element to a running total.
Step-4 − The method returns the sum of all elements in the matrix.
Algorithm-3
Step-1 − A 2D matrix is declared.
Step-2 − The user defined method is called to find the sum of all elements in the matrix.
Step-3 − The method uses the Stream API to convert the 2D matrix into a 1D stream of elements and reduce to find the sum of all elements in the stream.
Step-4 − The method returns the sum of all elements in the matrix.
Syntax
To get the length of an array (number of elements in that array), there is an inbuilt property of array i.e length
Below refers to the syntax of it −
array.length
where, ‘array’ refers to the array reference.
Multiple Approaches
We have provided the solution in different approaches.
Using Nested Loop
Using Stream API
Using Arrays.stream and flatMap:
Let’s see the program along with its output one by one.
Approach-1: By Using Nested Loop
In this approach, matrix elements will be initialized in the program. Then call a user defined method by passing the array as parameter and inside method as per the algorithm using nested loop calculates the sum of the elements of given matrix.
Example
public class Main { public static void main(String[] args) { // declare and initialize the 2D matrix int[][] inputMatrix = {{10, 20, 30}, {40, 50, 60}, {70, 80, 90}}; // Call the user-defined method to get the sum of all elements int sum = sumOfMatElmt(inputMatrix); // Print the result System.out.println("Sum of matrix elements: " + sum); } //user-defined method to find the sum of the elements public static int sumOfMatElmt(int[][] mat) { // declare and initialize the sum variable int sum = 0; for (int i = 0; i < mat.length; i++) { // initiate the looping over each column of the current row for (int j = 0; j < mat[i].length; j++) { // Add the current element to the sum sum += mat[i][j]; } } // Return the result return sum; } }
Output
Sum of matrix elements: 450
Approach-2: By Using Stream API
In this approach, matrix elements will be initialized in the program. Then call a user defined method by passing the array as parameter and inside method as per the algorithm using stream API calculates the sum of the elements of given matrix.
Example
import java.util.stream.IntStream; public class Main { public static void main(String[] args) { // declare and Initialize the 2D matrix int[][] inputMatrix = {{11, 22, 33}, {44, 55, 66}, {77, 88, 99}}; // Call the sumOfMatrixElements method to get the sum of all elements int sum = sumOfMatElmnt(inputMatrix); // Print the result System.out.println("Sum of matrix elements: " + sum); } public static int sumOfMatElmnt(int[][] mat) { // Create an IntStream for each row of the matrix // and use map to get the sum of each row // Finally, use sum method to get the sum of all rows return IntStream.range(0, mat.length) .map(i -> IntStream.of(mat[i]).sum()) .sum(); } }
Output
Sum of matrix elements: 495
Approach-3: By Using Arrays.stream and flatMap
In this approach, matrix elements will be initialized in the program. Then call a user defined method by passing the array as parameter and inside method as per the algorithm using Arrays.stream and flatMap calculates the sum of the elements of given matrix.
Example
import java.util.Arrays; import java.util.stream.IntStream; public class Main { public static void main(String[] args) { // Declare a 2D matrix int[][] matrix = {{12, 23, 34}, {45, 56, 67}, {78, 89, 90}}; // Call the calculateSumOfElements method to find the sum of all elements int sum = calculateSumOfElements(matrix); // Print the result System.out.println("The sum of all elements in the matrix is: " + sum); } public static int calculateSumOfElements(int[][] matrix) { // Use Arrays.stream and flatMap to convert the 2D matrix into a 1D stream of elements return Arrays.stream(matrix) .flatMapToInt(IntStream::of) .sum(); } }
Output
The sum of all elements in the matrix is: 494
In this article, we explored different approaches to find sum of matrix by using Java programming language.