Consider:
List<String> someList = new ArrayList<String>();
// add "monkey", "donkey", "skeleton key" to someList
for (String item : someList) {
System.out.println(item);
}
What would the equivalent for
loop look like without using the for each syntax?
A foreach loop syntax is:
Example:
Output:
WARNING: You can access array elements with the foreach loop, but you can NOT initialize them. Use the original
for
loop for that.WARNING: You must match the type of the array with the other object.
If you want to edit elements, use the original
for
loop like this:Now if we dump s to the console, we get:
The Java for each loop (aka enhanced for loop) is a simplified version of a for loop. The advantage is that there is less code to write and less variables to manage. The downside is that you have no control over the step value and no access to the loop index inside the loop body.
They are best used when the step value is a simple increment of 1 and when you only need access to the current loop element. For example, if you need to loop over every element in an array or Collection without peeking ahead or behind the current element.
There is no loop initialization, no boolean condition and the step value is implicit and is a simple increment. This is why they are considered so much simpler than regular for loops.
Enhanced for loops follow this order of execution:
1) loop body
2) repeat from step 1 until entire array or collection has been traversed
Example – Integer Array
The currentValue variable holds the current value being looped over in the intArray array. Notice there’s no explicit step value – it’s always an increment by 1.
The colon can be thought of to mean “in”. So the enhanced for loop declaration states: loop over intArray and store the current array int value in the currentValue variable.
Output:
Example – String Array
We can use the for-each loop to iterate over an array of strings. The loop declaration states: loop over myStrings String array and store the current String value in the currentString variable.
Output:
Example – List
The enhanced for loop can also be used to iterate over a java.util.List as follows:
The loop declaration states: loop over myList List of Strings and store the current List value in the currentItem variable.
Output:
Example – Set
The enhanced for loop can also be used to iterate over a java.util.Set as follows:
The loop declaration states: loop over mySet Set of Strings and store the current Set value in the currentItem variable. Notice that since this is a Set, duplicate String values are not stored.
Output:
Source: Loops in Java – Ultimate Guide
The Java for-each idiom can only be applied to arrays or objects of type *Iterable. This idiom is implicit as it truly backed by an Iterator. The Iterator is programmed by the programmer and often uses an integer index or a node (depending on the data structure) to keep track of its position. On paper it is slower than a regular for-loop, a least for "linear" structures like arrays and Lists but it provides greater abstraction.
Using older Java versions including
Java 7
you can useforeach
loop as follows.Following is the very latest way of using
foreach
loop inJava 8
(loop a List with
forEach
+ lambda expression or method reference)For more info refer this link.
https://www.mkyong.com/java8/java-8-foreach-examples/
It adds beauty to your code by removing all the basic looping clutter. It gives a clean look to your code, justified below.
Normal
for
loop:Using for-each:
for-each is a construct over a collection that implements Iterator. Remember that, your collection should implement Iterator; otherwise you can't use it with for-each.
The following line is read as "for each TimerTask t in list."
There is less chance for errors in case of for-each. You don't have to worry about initializing the iterator or initializing the loop counter and terminating it (where there is scope for errors).