0

Good afternoon Ive recently learned about steams in my Java class and would like to expand my knowledge.

I am trying to stream through a 2d array, and add the sum of the elements in the previous row to each element in the next row.

I also want to make this stream parallel, but this brings up an issue because if the stream begins working on the second row before the first is finished the the data integrity will be questionable.

Is there anyway to do this in java?

2
  • Streams are generally supposed to be stateless. This doesn't sound like a good use case. Commented Mar 5, 2020 at 22:07
  • Would a nested stream work? Where the first stream iterated through the rows and the nested one sums up each value in a column and passes it to the next row? Commented Mar 5, 2020 at 22:09

1 Answer 1

1

If I understood you correctly, this peace of code does what you are asking for:

    int[][] matrix = new int[][]{{1,2,3},{3,2,1},{1,2,3}};
    BiConsumer<int[], int[]> intArraysConsumer = (ints, ints2) -> {
        for (int i = 0; i < ints.length; i++) {
            ints[i] = ints[i] + ints2[i];
        }
    } ;
    int[] collect = Arrays.stream(matrix).collect(() -> new int[matrix[0].length], intArraysConsumer, intArraysConsumer);
    System.out.println(Arrays.toString(collect));

This outputs: [5, 6, 7]

For what I understand of the streams api, it will decide if running this in parallel, that's why you need to provide an creator of the object you need starting empty, a way to accumulate on it, and a way to combine two of the partial accumulation objects. For this particular case the accumulate and combine operations are the same.

Please refer to: https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#collect-java.util.function.Supplier-java.util.function.BiConsumer-java.util.function.BiConsumer-

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.