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];
}
marked as duplicatedoes not explain about how to do this with nested for loops. Also my logic is about counting such occurrences, the link does not explain that.forEachiteration. In Java 9 you could usetakeWhile. But even this would be an inefficient way to solve the problem: it's still quadratic, whereas you could do it linearly (but not with streams).Or you maintain two indices into the list for an element e and its e+k position in a single loop.Can you please explain what it means? I understand likeeis an element in the list, so see ife+kis also present in the list. Like this, I have to repeat for each element. Looks like what I am thinking is different from your point.index1, the index ofeat0. Findindex2, the index ofe+k, e.g. viaCollections.binarySearch. Now enter the loop: raiseindex1by one. Since the list is sorted, the neweis bigger than the old one, hence, the index ofe + kmust be bigger than the old one too. Raiseindex2until you either, founde+kor reached an element bigger thane+k. Repeat untilindex2reaches the end of the list. Then, you don’t need to raiseindex1any more as the correspondinge+kwouldn’t be in the list. So you’re done. The biggerk, the less elements you have to check…