Below examples uses different techniques to iterate over java collections. Use what’s suitable and easy for you in any situation.
-
Iterable.forEach method (Java 8)
Recently introduced in java 8, This method can be called on any
Iterable
and takes one argument implementing the functional interfacejava.util.function.Consumer
. e.g.Collection<String> collection = Arrays.asList("How", "To", "Iterate", "In", "Java"); collection.forEach(s -> System.out.println(s));
The Array class does not yet implement Iterable, so you cannot use this technique directly on arrays. -
Java “foreach” loop (Java 5)
The “foreach” loop syntax is:
for (Type var : Iterable<Type>) { // do something with "var" }
e.g.
Collection<String> collection = Arrays.asList("How", "To", "Iterate", "In", "Java"); for(String s : collection) { System.out.println(s); }
-
java.util.Iterator (Java 2)
Using Iterator is still very popular way to iterate over collections, mainly due to addtional methods it provide to manipulate the collection elements.
Collection<String> collection = Arrays.asList("How", "To", "Iterate", "In", "Java"); Iterator<String> itr = collection.iterator(); while(itr.hasNext()) { System.out.println(itr.next()); }
-
Traditional for loop
This is most appropriate when dealing with indexed collections such as list. It uses the standard for loop invented in the early 1970s in the C language. The loop syntax is:
for (init; test; change) { // do something }
e.g.
List<String> list = Arrays.asList("How", "To", "Iterate", "In", "Java"); for( int i=0; i < list.size(); i++ ) { System.out.println(list.get(i)); }
Happy Learning !!
References:
Leave a Reply