Java Fundamentals

Iterating with forEach

Angie Jones

Angie Jones

Java Champion
Java Fundamentals

Check out a free preview of the full Java Fundamentals course

The "Iterating with forEach" Lesson is part of the full, Java Fundamentals course featured in this preview video. Here's what you'd learn in this lesson:

Angie demonstrates using forEach(), a built-in convenience method, to iterate over a collection. The forEach() method can be used with all of the previously mentioned data structures.

Preview
Close

Transcript from the "Iterating with forEach" Lesson

[00:00:00]
>> So using the forEach method, is an even more straight forward approach to iterating over collections, and this is available on every collection and even on Mac. We are going to use forEach to print the elements of the fruit list, so back to our CollectionsDemo. I'm gonna uncomment out the listDemo.

[00:00:28]
And then here, I'm gonna comment out the enhanced for loop and I wanna use another one. All right, so this is so dead simple, you're gonna love it. We just say fruits.forEach. The end, that is my loop. And then I'm basically saying for every element that is in this collection, I want you to do something.

[00:00:59]
Inside of these parentheses is where we are going to provide the action that we want to occur. All right, so for, what do we wanna do? We basically wanna print something. Print each element, right? That's all we were doing. So we're gonna use a lambda expression. Okay, this is part of Java's like functional programming capabilities.

[00:01:27]
So now you're kind of dabbling in the functional programming side. So you got a little objectory, you got a little functional look at you, right? All right, in order to write a lambda expression, what you're gonna do is you're gonna provide a variable name for every element, right?

[00:01:47]
Just like we kind of did right here where we said string fruit over fruits except with the lambda expression, it's really common to just use a single letter versus a full variable name. Now you're more than welcome to use a full variable name but, it's really short term, and you just kind of do like f whatever.

[00:02:10]
F for fruit. All right, you look really cool with a single letter. Okay, I know what I'm doing. [LAUGH] All right, and then we'll say okay, for every f, I wanna print, I wanna print something out. And then what am I wanna print, I wanna print f itself dn, one line.

[00:02:38]
In a queue,
>> That's nice.
>> That's nice. All right, so let's just run it, make sure everything is working. Boom, so I did the exact same thing that we did with the enhanced for loop or that we did with like the big iterator. So I'll be honest with you, the iterator is played out.

[00:03:03]
I just taught it to you because if you have to read any legacy code, you might see it in there. I want you to know what it is. But if you have to write brand new code, don't pull the iterator out. Unless you're using like an older version of Java that doesn't have these features or, that's just like the way that it's done in that code base.

[00:03:26]
Sometimes people don't want you showing off with your new fancy tricks and stuff, but if it's a greenfield project, do not pull the iterator out. So this really slipped, right? Now in this case, this is equivalent to this loop where I only had one line that I was executing, but what if you wanted to do multiple lines there?

[00:03:49]
You could still use this approach. You simply would, let me make another one so that you have couple of examples. So what you would do is put a curly brace right there. So after the arrow, a curly brace, and then you could put whatever sentences, I mean whatever statements you want it so let's say we wanna say f equals, I don't know, we wanna append the string with the word fruit for example +f.

[00:04:24]
And then I wanna print out f or whatever. So that short lambda expression, just to give you a little bit more context on that, it is a block of code that works basically like a method, right? It accepts parameters, it returns a value. They differ from methods in that they don't have names.

[00:04:45]
And they're executed inline versus being called by other methods. So if you're from the JavaScript world, this is like equivalent to an anonymous function. All right, let's look at forEach for a map, cuz map always has to be a little different. All right, so if I go to the map, I'm gonna comment out this one.

[00:05:18]
All right, so we'll say fruitCalories.still forEach. I don't have to get an entry set or anything like that. So still much simpler. Okay, it gets a little different but it's still much better than everything else. So as opposed to just saying, like, the one variable, because it's a map, you're dealing with two things, the key and the value.

[00:05:45]
So in parentheses, you would specify two different variables versus one. We use K for key, V for value, and then the rest is the same. You do your arrow function. And then, whatever. So you can say like system.out.println. And maybe I wanna print both the key and the value, that's how you reference them with the K, and the V.

[00:06:17]
Plus V and that's it. That's really simple too, right? Much better than, where's that iterator one? Did I write it in here? I might have not. I only showed slides, right? It was too horrible to put you through, like writing it, right? But the iterator for map was like, so you don't have to live like that anymore.

[00:06:43]
And then even the forEach which was much better, it still is a little bit lengthy compared to just using, I mean the enhanced for loop compared to like just the four each. Questions? You like it? Okay, there's another little thing I wanna show you. If we go back to the listDemo.

[00:07:11]
All right, so here, We said, okay, I have F, I wanna just print out something. There's another little like shortcut syntactically that you can use and these are called method references. I could just say The class name, so remember I said that the lambda expressions are anonymous functions, they take input, they return output, right?

[00:07:48]
So what we were doing with the f in the arrow and then we were saying print F, basically, we're using f as the input yada, yada. This is a shorthand since it's only a single method that's being used, I can just say the class name in our case, it's system.out.

[00:08:09]
But if it was another class that just had a method, you would just say that class name. And then you would say colon, colon, and the method name. So this is called a method reference. That way it knows, okay, the input that you were gonna use is whatever is like the next object.

[00:08:27]
I'll pass that to this method and then we're good to go, right? And you don't have to specify that with the long form. Now, you can, I'll put the other way just so you have it here. It's definitely fine to do it that way, but you don't have to.

[00:08:45]
This is a shortcut. And that only works when it's just a single method that you're trying to execute if you had like the curly braces and you were trying to do multiple methods this does not work.
>> If whatever method that you're calling with this way of doing it has a little like, private helper method it uses you accomplish that task cuz I couldn't change anything.

[00:09:14]
>> No it's still gonna call that method.
>> All right, so just gonna run as normal.
>> It's gonna run as normal, it's just basically a shortcut way to write it to, in your code, but under the covers, it's gonna do the exact same thing.
>> Does it have to be as guessing crinoline is a static method does it have to be static or can you use-

[00:09:31]
>> It doesn't, that's a great question because we're referencing this almost like we do static things where we say class.method, right? If this was not a static method, we could still do the class with the colon-colon in the non-static method and that would be fine too. Yeah. Any other questions?

[00:09:58]
>> Does it work for maps?
>> Yes, it does.
>> See you could read a
>> So with well, I don't know, cuz method takes two, I mean maps takes two
>> Yes if you had a custom method that took
>> A bike
>> Let's try it out, I don't know, let's just try it out.

[00:10:19]
>> I'll tell you you folks are adventurous. Okay, and let's say that. Okay, I don't like that. Ambiguous. Man both println. You get yourself in trouble, right? Because you're no longer explicitly like when I did this println, I'm explicitly saying which one of those and apparently there's an overloaded method that takes a boolean and now it just doesn't know what to do [LAUGH].

[00:10:58]
So it did when it was a single argument but with the two I don't know it just gets it gets confused, so short answer is no.
>> What do you call that again?
>> Method reference. So it's just a little syntactic sugar. Same thing as the lambda expression, just kind of shorthand.

Learn Straight from the Experts Who Shape the Modern Web

  • In-depth Courses
  • Industry Leading Experts
  • Learning Paths
  • Live Interactive Workshops
Get Unlimited Access Now