Wednesday, November 6, 2013

Usage of foreach loop inside foreach loop, and also an example of iterating a List of Map objects ....9/10

Hi,

This page explain how to iterate a List object of Map objects using foreach loops.

Take a class Test.java

source :
package com.nagarjuna.core.collections:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Test {

public static void main(String[] args) {

List> lMap = new ArrayList>();

Map m = new HashMap();
m.put("1", "one");
m.put("3", "three");
m.put("2", "two");
m.put("0", "zero");

Map m1 = new HashMap();
m1.put("1", "one");
m1.put("0", "zero");
m1.put("2", "two");
m1.put("3", "three");

Map m2 = new HashMap();
m2.put("3", "three");
m2.put("1", "one");
m2.put("2", "two");
m2.put("0", "zero");

Map m3 = new HashMap();
m3.put("1", "one");
m3.put("2", "two");
m3.put("3", "three");
m3.put("0", "zero");

// now trying to put these map objects into a lis object


lMap.add(m1);
lMap.add(m2);
lMap.add(m3);
lMap.add(m2);
lMap.add(m);


// trying to print the key value pairs of each map from the list above

for (Map map : lMap) { //for each map obeject in list object
      System.out.println(lMap.indexOf(map)); //will print the index number of current map object in list
for (String key : map.keySet()) { // for each map's keyset object..iterating this keyset

System.out.println(key + ":" + map.get(key));
}//end inner loop

System.out.println("----------------------------------"); // end of first index of list object
}//end outer loop

}

}//end class


Just observe the above foreach loop code to understand how to use when we have to iterate a collection of collection of like this.



No comments:

Post a Comment