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.


  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())

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?

  • 1
    \$\begingroup\$ 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? \$\endgroup\$ – harold Nov 4 '17 at 13:40
  • \$\begingroup\$ 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. \$\endgroup\$ – Carrein Nov 4 '17 at 13:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.