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
  • 986,068
  • 189
  • 2,389
  • 2,491
Alex Burton
  • 49
  • 1
  • 8
  • 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
  • 90,003
  • 9
  • 87
  • 127
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
  • 27,626
  • 16
  • 90
  • 108