【问题标题】:How to loop through ALL content of HashMap [duplicate]如何遍历HashMap的所有内容[重复]
【发布时间】:2015-08-28 23:52:55
【问题描述】:

如何遍历 HashMap 的所有内容? 我只得到最后一位

   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);
    }

我只得到最后一个:

Key = company, Value = company1
Key = name, Value = name1

【问题讨论】:

  • 您正在覆盖相同键 namecompany 的值。也许您想要一个带有 Set 值的多地图?

标签: java android


【解决方案1】:

列表中有多个地图。您需要遍历列表,然后遍历列表内的地图。

for(HashMap<String, String> curMap : list) {
    //Put your loop over the map here.
}

【讨论】:

  • 非常感谢!!我把它当作一张带索引的地图。
【解决方案2】:

先遍历列表,然后遍历地图。

for(Map<String, String> myMap: list){
    for (Map.Entry<String, String> entry : myMap.entrySet()){
           Log.w("dd:", "Key = " + entry.getKey() + ", Value = " +             
              entry.getValue());
          }
}

【讨论】:

  • 阿皮特?你认识亚历克斯伯顿吗?
猜你喜欢
  • 2010-11-07
  • 2020-05-15
  • 2018-10-15
  • 2019-06-24
  • 1970-01-01
  • 2022-01-16
  • 1970-01-01
  • 2011-09-11
  • 2020-02-14
相关资源
最近更新 更多