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.
Assume that the list provided is already sorted. Now I want to find the number of elements whose difference is equal to some value say k
.
public static int getCount(List<Integer> list, int k) {
int result = 0;
for (int i = 0; i < list.size(); i++) {
for (int j = i + 1; j < list.size(); j++) {
if (list.get(j) - list.get(i) > k) {
break;
}
if (list.get(j) - list.get(i) == k) {
result++;
}
}
}
return result;
}
Now the same logic using Java 8 streams, here to skip inner loop I have used return
statement, but as the inner loop is not broken the performance is not improved.
public static int getCount(List<Integer> list, int k) {
int[] result = { 0 };
IntStream.range(0, list.size()).forEach(i -> {
IntStream.range(i + 1, list.size()).forEach(j -> {
if (list.get(j) - list.get(i) >= k)
return;
if (list.get(j) - list.get(i) == k) {
result[0]++;
}
});
});
return result[0];
}