#Intellij is complaining about this code, not sure why

1 messages · Page 1 of 1 (latest)

lusty sinew
#
    public K get(int i) {
        int j = 0;
        this.forEach((K key, V value) -> {
            if (j == i) {
                return key;
            }
            j++;
        });
        return null;
    }```
its saying "variable used in lambda expression should be final or effectively final" (about j), and gives the option to convert j to atomic. Im wondering what that means, and what atomic is. (K and V are generics, this class extends HashMap)
slender agateBOT
#

This post has been reserved for your question.

Hey @lusty sinew! Please use /close or the Close Post button above when you're finished. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

slow bane
#

IntelliJ offers to replace with an AtomicInteger, because then you wouldn't need to reassign it. You would just need to call a method to update it.

#

That is, however, a hacky solution that shouldn't be used. In your case, that wouldn't even solve the entire problem

#

Indeed, you're trying to return from inside the lambda, which can't be done either

#

Your better bet is to get rid of the lambda altogether, and to iterate over the Map's entries instead.

lusty sinew
#

Im not sure how to do that

slow bane
#
for(Map.Entry<K, V> entry : this.entrySet()) {
#

(Come to think of it, the better solution is to stream the keys, skip i-1 of them, and return the first found in the rest)

lusty sinew
#

something like this? java for (K key : this.keySet()) { if (j == i) return key; j++; }

slow bane
#

Yeah, it's even better

lusty sinew
#

cool, thanks

slender agateBOT
# lusty sinew cool, thanks

If you are finished with your post, please close it.
If you are not, please ignore this message.
Note that you will not be able to send further messages here after this post have been closed but you will be able to create new posts.