0

I have this piece of code and i dont understand why I m getting the following error:

local variables referenced from a lambda expression must be final or effectively final

Here is my code

    public int firstMissingPositive(int[] nums) {

        int k;

        for (int i = 1;; i++) {
            if (!Arrays.stream(nums).anyMatch(x -> x != i)) {
                k = i;
                break;
            }
        }
        return k;
    }
Stefan Zobel
  • 3,182
  • 7
  • 28
  • 38
  • 1
    If you typed *local variables referenced from a lambda expression must be final or effectively final* or some combination of it, SO would have shown you several duplicates. – achAmháin Nov 06 '18 at 17:26
  • The code has very bad performance (_O(n^2)_). You can get better performance by either sorting the array, or by building a `boolean[]` of found values, or ... – Andreas Nov 06 '18 at 17:35
  • For the future: please spend some time to find a *reasonable* title for your question. This is a Q/A community, all content should be written to be helpful for future readers. Few future readers will find *How can i get around this?* to be a helpful starting point ... – GhostCat Nov 07 '18 at 15:35
  • Sorry for that today. I will keep that in my mind. – Jasmin Jasko Merušić Nov 07 '18 at 15:50

1 Answers1

3

Because i is not effectively final (see i++), and it must be to be used in a lambda expression.

It is easy enough to fix, by assigning to a new local variable inside the loop:

public int firstMissingPositive(int[] nums) {
    int k;
    for (int i = 1;; i++) {
        final int j = i;
        if (! Arrays.stream(nums).anyMatch(x -> x != j)) {
            k = j;
            break;
        }
    }
    return k;
}
Andreas
  • 154,647
  • 11
  • 152
  • 247