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.
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())