Jenkov.com
Tutorials About




Java's Generic For Loop


Last updated: 2014-06-23

Java's Generic's has a new for loop. This new for loop is also sometimes referred to as the "for each" loop. This new for loop makes it easier to iterate generic collections. For instance, iterating generic Set's or List's.

Here is a simple example that iterates a generic List:

List<String> list = new ArrayList<String>;

for(String aString : list) {
    System.out.println(aString);
}

Notice how a String variable is declared inside the parantheses of the for-loop. For each iteration (each element in the List) this variable contains the current element (current String).

Here is an example that uses a Set:

Set<String> set = new HashSet<String>;

for(String aString : set) {
    System.out.println(aString);
}

Notice how the for-loop looks the same as for a List.

Here is an example for a Map

Map<Integer, String> map = new HashMap<Integer, String>;

//... add key, value pairs to the Map

for(Integer aKey : map.keySet()) {
    String aValue = map.get(aKey);
    System.out.println("" + aKey + ":" + aValue);
}

for(String aValue : map.values()) {
    System.out.println(aValue);
}

Notice how an Integer and a String variable is declared inside the parantheses of each for-loop. For each iteration (each element in the Map's key set or value collection) this variable contains the current element (current Integer or String).



Connect with me: Newsletter - Get all my free tips!
     



Close TOC
This website uses cookies to improve the user experience and gather statistics. Our advertisers use cookies too (3rd party cookies), to provide more relevant ads. Continued use of this website implies that you accept the use of cookies on this website. We do not share our cookies with our advertisers, and our advertisers do not share cookies with us.
OK