• Post Reply Bookmark Topic Watch Topic
  • New Topic

foreach and lambas

 
Karina Guenther
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Where would you use a forEach( lambda) rather than a for loop?

IE: would you write something like this using a forEach?


If you could re-write this as a lamba how? I've played around with it looking at some examples and can't get it to work. I've thought that perhaps it's not supposed to.

examples:



 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 35744
412
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The for loop in your example does two things. It prints out the values in a list and counts how many of them contain a specific String. I would do this in two parts.

First I use a lamba to filter, but not a forEach call. This uses functional programming to filter/count the matches.

As for the second, using a println in a forEach works fine. What error did you get when you tried it? Your functional programming example doesn't follow because it declares one list but tries to operate on another.


 
Sean Corfield
Ranch Hand
Posts: 311
13
Clojure Linux Mac OS X Monad
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can simplify that last line by using a method reference:
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 35744
412
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Sean! I forgot about that. I've been doing most of my functional programming in Groovy so far.
 
Richard Warburton
Author
Greenhorn
Posts: 22
7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Karina Guenther wrote:Where would you use a forEach( lambda) rather than a for loop?

IE: would you write something like this using a forEach?


If you could re-write this as a lamba how? I've played around with it looking at some examples and can't get it to work. I've thought that perhaps it's not supposed to.

examples:





Hi Karina,

Thanks for the question. What your for loop is doing is mutating the state of an accumulator variable, which is something you don't want to be doing within a forEach. A better approach would be to use streams in general to rewrite the code. The answer by Jeanne Boyarsky demonstrates this approach and looks like a sensible way to go.

I don't object to using forEach where its appropriate but doing lots of calculation in a forEach rather than using streams looks like a bit of a code smell to me.

regards,

Richard
 
Karina Guenther
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks so much for your answers. It's as important to me to learn when and when not to use the new functionality as how to use it.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!