For-each vs Iterator. Which will be the better option
Consider the following scenario.
List<String> list = new ArrayList<>();
Now I added the String
values for this list.
I used following ways to go each and every element in the list.
Option one- use for-each
for (String i : list) {
System.out.println(i);
}
Option two- use Iterator
Iterator it=list.iterator();
while (it.hasNext()){
System.out.println(it.next());
}
I just want to know is there any performance advantage if I use for-each
instead of Iterator
. And also is it a bad practice to use Iterator now a days in Java?
for-each
is syntactic sugar for using iterators
(approach 2).
You might need to use iterators
if you need to modify collection in your loop. First approach will throw exception.
for (String i : list) {
System.out.println(i);
list.remove(i); // throws exception
}
Iterator it=list.iterator();
while (it.hasNext()){
System.out.println(it.next());
it.remove(); // valid here
}
The difference is largely syntactic sugar except that an Iterator can remove items from the Collection it is iterating. Technically, enhanced for loops allow you to loop over anything that's Iterable, which at a minimum includes both Collections and arrays.
Don't worry about performance differences. Such micro-optimization is an irrelevant distraction. If you need to remove items as you go, use an Iterator. Otherwise for loops tend to be used more just because they're more readable ie:
for (String s : stringList) { ... }
vs:
for (Iterator<String> iter = stringList.iterator(); iter.hasNext(); ) {
String s = iter.next();
...
}
for-each
is an advanced looping construct. Internally it creates an Iterator and iterates over the Collection. Only possible advantage of using an actual Iterator object over the for-each
construct is that you can modify your collection using Iterator's methods like .remove()
. Modifying the collection without using Iterator's methods while iterating will produce a ConcurrentModificationException.
Best way to do this is in java 8 is,
list.forEach(System.out::println);
Here are some useful links.
Java 8 Iterable.forEach() vs foreach loop
http://www.javaworld.com/article/2461744/java-language/java-language-iterating-over-collections-in-java-8.html
https://docs.oracle.com/javase/8/docs/api/java/lang/Iterable.html
Simple answers: No and no.
Internally the for-each
loop creates an Iterator
to iterate through the collection.
The advantage of using the Iterator
explicitly is that you can access the Iterator
s method.