2

How to loop through ALL content of HashMap? I only get last put

   ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();

// 0
    HashMap<String, String> map = new HashMap<String, String>();
    map.put("name", "name0");
    map.put("company", "company0");
    list.add(map);
// 1
    map = new HashMap<String, String>();
    map.put("name", "name1");
    map.put("company", "company1");
    list.add(map);


    for (String key : map.keySet()) {
        String value = map.get(key);
        Log.w("dd:", "Key = " + key + ", Value = " + value);
    }

I only get last put:

Key = company, Value = company1
Key = name, Value = name1
CommonsWare
  • 954,112
  • 185
  • 2,315
  • 2,367
  • You are overwriting your values for the same keys `name` and `company`. Perhaps you want a multi-map with `Set` values? – javabrett Jun 12 '15 at 21:27

2 Answers2

6

You have multiple maps in a list. You need to loop over the list, then loop over the map inside the list.

for(HashMap<String, String> curMap : list) {
    //Put your loop over the map here.
}
Gabe Sechan
  • 84,451
  • 9
  • 82
  • 121
0

Iterate over list first and then over map.

for(Map<String, String> myMap: list){
    for (Map.Entry<String, String> entry : myMap.entrySet()){
           Log.w("dd:", "Key = " + entry.getKey() + ", Value = " +             
              entry.getValue());
          }
}
Arpit Aggarwal
  • 24,784
  • 14
  • 83
  • 102