Monday 29 June 2015

Enhanced for loop


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

1 comment:

  1. Casino in South Korea | MapyRO
    View 속초 출장안마 casino map. Casino. Harrah's North 오산 출장안마 Korea - 남양주 출장안마 Harrah's 광주 출장마사지 North Korea. South Korea. Map. 경산 출장마사지 Harrah's North Korea.

    ReplyDelete