Intellij is complaining about this code, not sure why

public K get(int i) {
int j = 0;
this.forEach((K key, V value) -> {
if (j == i) {
return key;
}
j++;
});
return null;
}
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)
9 Replies
JavaBot
JavaBot2y ago
This post has been reserved for your question.
Hey @blockgoblin31! 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.
Kyo-chan
Kyo-chan2y ago
Inside a lambda, you can't reassign a local variable that was declared outside of that lambda. Here you're reassigning j in the lambda, despite it's a local variable declared in get(). That doesn't work 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.
blockgoblin31
blockgoblin31OP2y ago
Im not sure how to do that
Kyo-chan
Kyo-chan2y ago
for(Map.Entry<K, V> entry : this.entrySet()) {
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)
blockgoblin31
blockgoblin31OP2y ago
something like this?
for (K key : this.keySet()) {
if (j == i) return key;
j++;
}
for (K key : this.keySet()) {
if (j == i) return key;
j++;
}
Kyo-chan
Kyo-chan2y ago
Yeah, it's even better
blockgoblin31
blockgoblin31OP2y ago
cool, thanks
JavaBot
JavaBot2y ago
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.
JavaBot
JavaBot2y ago
Post Closed
This post has been closed by <@501514065068294154>.

Did you find this page helpful?