首页 > 解决方案 > 遍历 Map 的 ArrayList 的 ArrayList

问题描述

我使用 SimpleExpandableListAdapter 为我的应用程序创建 ExpandableListView。我想更好地了解如何使用列表和地图以及它们在实践中的作用。

 //collection for elements of a single group;
ArrayList<Map<String, String>> childDataItem;

//general collection for collections of elements
ArrayList<ArrayList<Map<String, String>>> childData;


Map<String, String> m;

我知道如何遍历 Maps 的 ArrayList,这对我来说不是问题,但我被卡住了。

childData = new ArrayList<>();
    childDataItem = new ArrayList<>();
    for (String phone : phonesHTC) {
        m = new HashMap<>();
        m.put("phoneName", phone);
        childDataItem.add(m);
    }
    childData.add(childDataItem);

    childDataItem = new ArrayList<>();
    for (String phone : phonesSams) {
        m = new HashMap<String, String>();
        m.put("phoneName", phone);
        childDataItem.add(m);
    }
    childData.add(childDataItem);

    // создаем коллекцию элементов для третьей группы
    childDataItem = new ArrayList<>();
    for (String phone : phonesLG) {
        m = new HashMap<String, String>();
        m.put("phoneName", phone);
        childDataItem.add(m);
    }
    childData.add(childDataItem);

而且我想记录 childData 包含的内容(<ArrayList<Map<String, String>>),但我不确定我做对了。(第二个循环是 Map 迭代的简单 ArrayList)

    for (ArrayList<Map<String, String>> outerEntry : childData) {
       for(Map<String, String> i:outerEntry ) {
           for (String key1 : i.keySet()) {
               String value1 = i.get(key1);
               Log.d("MyLogs", "(childData)value1 = " + value1);
               Log.d("MyLogs", "(childData)key = " + key1);
           }
         }


        for (Map<String, String> innerEntry : childDataItem) {
            for (String key : innerEntry.keySet()) {
                String value = innerEntry.get(key);
                Log.d("MyLogs", "(childDataItem)key = " + key);
                Log.d("MyLogs", "(childDataItem)value = " + value);
            }
        }
    }

标签: javaandroidarraylist

解决方案


所以你可能知道,数组列表只是数据对象的顺序存储。而映射是键值对映射,其中键用作查找并且必须是唯一的。也就是说,在一个Map你可能有很多重复的值,但只有一个键。

至于迭代 aMap你可以使用一个条目集,这使它更容易一些。因此,如果您想迭代一个类型的对象,<ArrayList<Map<String, String>>对于您的 childDataItem 类,它看起来像这样。

for(Map<String, String> map : childDataItem){

  //Take each map we have in the list and iterate over the keys + values
  for(Map.Entry<String, String> entry : map){
    String key = entry.getKey(), value = entry.getValue();
  }

}

在您的其他情况下,示例是相同的,只是您有另一层数组列表。

for(List<Map<String, String>> childDataItemList : childData){

  for(Map<String, String> map : childDataItemList){

    //Take each map we have in the list and iterate over the keys + values
    for(Map.Entry<String, String> entry : map){
      String key = entry.getKey(), value = entry.getValue();
    }

  }

}

推荐阅读