This is one of the problems where a for
loop would be more readable over streams.
int sum = 0;
int random = 4;
int[] arr = {3, 5, 6, 1};
int index = arr.length - 1;
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
if (sum > random) {
index = i;
break;
}
}
System.out.println(index);
I want to see if there are better, more Java, ways which use stream, reduce, parallel stream, or etc. that comes to your mind.
A for
loop through an array
is extremely lightweight both in terms of heap and CPU usage. If raw speed and memory thriftiness is a priority, using a stream is worse. The decision whether to use Streams or not should not be driven by performance consideration, but rather by readability. When it really comes to performance, there are other considerations.
Streams also follow lazy evaluation: Computation on the source data is only performed when the terminal operation is initiated, and source elements are consumed only as needed. All intermediate operations are lazy, so they’re not executed until a result of a processing is actually needed.
What you want is intermediate results at every index to compare it with the random number, personally, I'd prefer writing a normal for
loop in this case.
Parallel Streams do not guarantee the order of traversal, so it'd be the wrong implementation choice here.
You can read more about for loops vs streams here