# Parallel matrix multiplication in Java with streams

This StackOverflow post highlights how to do matrix multiplication using Java's stream.

With Java streams, there is a new way to enable concurrent threading with the Java's parallel stream.

ParallelMatrixMultiplication.java

  public Matrix multiply(Matrix v) {
return new Matrix(Arrays.stream(this.m).parallel()
.map(row -> IntStream.range(0, v.m[0].length)
.mapToDouble(i -> IntStream.range(0, v.m.length)
.mapToDouble(j -> row[j] * v.m[j][i]).sum())
.toArray())
.toArray(double[][]::new));
}


As you can see, I simply added the .parallel() method.

This function works fine as a noticeable speed up is seen for larger matrices.

I'm curious then, is there a way to optimize or speed this function up further?

• Certainly it can be done faster, since there is no cache optimization by loop tiling here. But I wouldn't know how to do that with streams. Are non-stream implementations allowed? – harold Nov 4 '17 at 13:40
• Non stream is okay as well, just that I'm not familiar with concurrent processing i.e. fork/join and .parallel() was the easiest to implement. – Carrein Nov 4 '17 at 13:46