I have below code where I am using nested for loops and I have some condition that breaks the inner for loop, and this improves the performance of this code.
public static int getMaxValue(List<Integer> list) {
int result = -1;
for(int i=0; i<list.size(); i++) {
for(int j=i+1; j<list.size(); j++) {
if(list.get(j) - list.get(i) <= 0) break;
if(list.get(j) - list.get(i) > result) {
result = list.get(j) - list.get(i);
}
}
}
return result;
}
Now how can I use Java 8 streams to do the same logic? I have come up with below code:
public static int getMaxValue(List<Integer> list) {
int[] result = { -1 };
IntStream.range(0, list.size()).forEach(i -> {
IntStream.range(i + 1, list.size()).forEach(j -> {
if(list.get(j) - list.get(i) <= 0) return;
if(list.get(j) - list.get(i) > result[0]) {
result[0] = list.get(j) - list.get(i);
}
});
});
return result[0];
}
Here I cannot use a break
statement in java streams, so I have used return
statement, but that still runs the inner loop, as it will not break it the performance is not improved.