java - 遍历 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);
}
}
}
解决方案
所以你可能知道,数组列表只是数据对象的顺序存储。而映射是键值对映射,其中键用作查找并且必须是唯一的。也就是说,在一个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();
}
}
}
推荐阅读
- ios - UIImagePickerControllerDelegate 未被调用,所选图像从未显示
- javascript - htmlparser2 - 替换 html 字符串中所有 href 属性的值
- python - 为每个 id 分区添加下月初
- python - 如何更改已被 Google 索引的 Django 网站的 URL 结构?
- sql - 添加工作班次 3 (SUM) 时的 SQL Server 疑问
- php - 使用单个请求将数据和文件提交到服务器
- r - 带有来自 Excel 数据的多条线的线图
- javascript - RXJS 显示一个时间范围内的累积结果
- c++ - 声明二维向量大小时出错
- visual-studio-code - 如何在 VSCode 的 Markdown 预览中启用复选框