How to convert nested loops to nested Streams?

Viewed 895

Let's say I have an int array and I want to find all pairs that sum to zero. In the old days I would do something like this:

public static int count(int[] a) {
    int cnt = 0;
    int N = a.length;
    for (int i = 0; i < N; i++) {
        for (int j = i + 1; j < N; j++) {

        if (a[i] + a[j] == 0) {
            cnt++;
        }
       }
    }
    return cnt;
    }

Now I'm having some trouble converting this to streams.

I tried the following approach but I get a IllegalStateException:

final IntStream stream1 = Arrays.stream(a);
final IntStream stream2 = Arrays.stream(a);
long res = stream1.flatMap(i -> stream2.filter(j -> (j + i == 0))).count();
2 Answers
Related