Java For Each Loop

1 03 2013

Java For Each Loop Syntax

Java does not have a foreach key word like some other programming languages do. Instead, it has an enhanced for loop that accomplishes the same thing. The syntax is as follows:

for(type itr-var : collection) statements

“Type” is what it says it is. It is the type for the itr-var.

“Itr-var” is the iteration variable. It will hold each member of the collection as you iterate through the loop.

“Collection is the collection of objects you’re cycling through.

Example:

Let’s say you have an array of numbers call nums. An array is a collection. So let’s say you want to iterate through that collection. Your for each loop would look like this:

for(int x : nums)
{
    statements
}

Think of it like this: “For each int x in the collection nums do…” The statements inside the code block following the “for-each” are automatically executed.

About these ads

Actions

Information

One response

1 03 2013
Ben

Looping over a Map :

HashMap map = new HashMap();
map.put(“java”, “noobie”);
map.put(“javanoobie”, “learning java”);

for (Map.Entry entry : map.entrySet())
{
System.out.println(entry.getKey() + ” -> ” + entry.getValue());
}

Or, if you only want the keys :

for(String entry : map.keySet())

Or, if you only want the values :

for(Object entry : map.values())

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s




Follow

Get every new post delivered to your Inbox.

Join 177 other followers

%d bloggers like this: