• Post Reply Bookmark Topic Watch Topic
  • New Topic

ForEach with Lambda  RSS feed

 
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi i am trying to change my foreach loop from traditional oop to lambda but lambda is complaining that the valuable should be declared as final

 
Saloon Keeper
Posts: 7993
143
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your lambda will work if your remove the for-loop, because the compiler will see that the counter variable is effectively final.

However, the lambda itself will only see one value for counter. If you want to do this in a functional way, we have a topic about that here: https://coderanch.com/t/670504/java/java/Features-Java#3133242

You'll notice that the solution is quite contrived. In short, you're better off with a plain old for-loop.
 
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's correct. Everything inside a lambda must be one of the following:
- an argument to the lambda (e.g. option).
- a local variable that is effectively final. That means that it's either explicitly final, or it never changes its value.
- a non-final static or instance field.

In this case, you're using counter, but because it has changed inside the method, it's not effectively final and therefore cannot be used.
 
Molayo Decker
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Mehn...It's not worth using lambda for this method then. I am trying to eliminate a lot of boilerplate code but it seems i have to forgo this one.

 
Stephan van Hulst
Saloon Keeper
Posts: 7993
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I wouldn't say that a for-loop is necessarily boilerplate. Even if lambdas allowed you to alter a local variable, you would still end up with roughly the same amount of code.
 
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The fact that we now have the foreach method on collections and lambdas indeed does not mean that you should never use a for loop again and that you should replace all for loops in your code with this.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!