In this tutorial, we will see “How to find the sum/add of two matrices using Java 8 Streams?”
Find sum of two matrices using Java 8 Streams API
Java 8 – Find Sum of Two Matrices? (Simplest Example) Click To Tweet
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 28 29 30 | /** * Using Java 8, Find the Sum of Two Matrices * @author Deepak Verma * */ import java.util.stream.IntStream; public class Find_Sum_Of_Two_Matrices_Java8_Example { public static void main(String[] args) { int[][] matrix1 = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; int[][] matrix2 = {{9, 8, 7}, {6, 5, 4}, {3, 2, 1}}; int[][] result = new int[matrix1.length][matrix1[0].length]; IntStream.range(0, matrix1.length).forEach(i -> IntStream.range(0, matrix1[0].length).forEach(j -> result[i][j] = matrix1[i][j] + matrix2[i][j] ) ); for (int[] row : result) { for (int value : row) { System.out.print(value + " "); } System.out.println(); } } } |
Output:
1 2 3 | 10 10 10 10 10 10 10 10 10 |
Find sum of two matrices using Java 8 Streams API
Java 8 – Find Sum of Two Matrices? (Simplest Example) Click To Tweet
Do you like this Post? – then check my other helpful posts:
- Convert a Stream to a List in Java 8
- Stream maptoint in Java 8 with examples
- Double the numbers of specified ArrayList using Streams
- Double the even / odd numbers of a specified ArrayList using Streams
- How to check if Number is Prime or not using Streams
- Retrieve Even/Odd Numbers within the Range using Java 8 Streams
- How to add/sum up the ArrayList integers using Java8 Streams
- Generate Prime Numbers in Java 8 using Streams
- Comparator example – Collections sort with/without Lambda in Java 8
- How to pass function as a parameter in a method in Java 8?
- Remove duplicates from ArrayList in Java 8
- ForEach examples for Map/List in Java 8
Other Useful References: