In  this tutorial, we will see “Program to Multiply two matrices using Java 8 Streams?”

program to multiply two matrices using Java 8 Stream

Java 8 – Program to Multiply Two Matrices? (Simplest Example) Share on X

import java.util.stream.IntStream;

/**
 * Using Java 8, Find the Multiplication of Two Matrices
 * @author Deepak Verma
 *
 */

public class Program_to_Find_Multiplication_of_Two_Matrices_Java8_Example {

	public static void main(String[] args) {
		
		int matrix1[][]={{1,1,1},{2,2,2},{3,3,3}};    
		int matrix2[][]={{1,1,1},{2,2,2},{3,3,3}}; 

		int rows1 = matrix1.length;
		int cols1 = matrix1[0].length;
		int rows2 = matrix2.length;
		int cols2 = matrix2[0].length;
		
		if (cols1 != rows2) {
			throw new IllegalArgumentException("Matrices can't be multiplied: " + cols1 + " != " + rows2);
		}
		
		int[][] result = new int[rows1][cols2];
		IntStream.range(0, rows1).parallel().forEach(i ->
		IntStream.range(0, cols2).parallel().forEach(j ->
		result[i][j] = IntStream.range(0, cols1).parallel()
		.map(k -> matrix1[i][k] * matrix2[k][j])
		.sum()));

		for (int[] row : result) {
			for (int value : row) {
				System.out.print(value + " ");
			}
			System.out.println();
		}
	}
}

 

Output:

6 6 6 
12 12 12 
18 18 18

program to multiply two matrices using Java 8 Stream

Java 8 – Program to Multiply Two Matrices? (Simplest Example) Share on X

Do you like this Post? – then check my other helpful posts:

Other Useful References:

Author

  • Deepak Verma

    Deepak Verma is a Test Automation Consultant and Software development Engineer for more than 10 years. His mission is to help you become an In-demand full stack automation tester.

    He is also the founder of Techndeck, a blog and online coaching platform dedicated to helping you succeed with all the automation basics to advanced testing automation tricks.

    View all posts