如图:

编写Java程序,使用List集合和Map集合输出 市和区_迭代器

代码:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

public class Test1 {
public static void main(String[] args) {
//云南省的 - 市
ArrayList<String> ynCity = new ArrayList<>();
ynCity.add("昆明市");
ynCity.add("昭通市");
ynCity.add("大理市");
ynCity.add("丽江市");
//湖南省的 - 市
ArrayList<String> hnCity = new ArrayList<>();
hnCity.add("长沙市");
hnCity.add("岳阳市");
hnCity.add("常德市");
hnCity.add("永州市");
//将市 和 区 存入Map集合
HashMap<String, ArrayList<String>> provinceCity = new HashMap<String, ArrayList<String>>();
provinceCity.put("云南省",ynCity);
provinceCity.put("湖南省",hnCity);
//将省和市存入countries Map集合中
HashMap<String, HashMap<String,ArrayList<String>>> countries = new HashMap<String,HashMap<String,ArrayList<String>>>();
countries.put("中国",provinceCity);
// countries.put("美国",provinceCity);//这里只写了中国的省和市这行注释掉

Set<String> countriesMapkey = countries.keySet();//得到Map 集合 countries的键 存入countriesMapkey中
Iterator it1 = countriesMapkey.iterator();//用键创建一个迭代器
while (it1.hasNext()) {
Object countriesMapkeys = it1.next();//遍历得到键集合存入countriesMapkeys
System.out.println(countriesMapkeys);
HashMap<String, ArrayList<String>> countriesMapValue = countries.get(countriesMapkeys);//得到键集合对应的值存入countriesMapValue
Set<String> provinceCityMapKey = countriesMapValue.keySet();//得到Map集合中provinceCity的键

Iterator it2 = provinceCityMapKey.iterator();//创建一个迭代器
while (it2.hasNext()) {
Object provinceCityMapKeys = it2.next();//得到Map 集合 provinceCity的键 存入countriesMapkey中
System.out.println(" "+provinceCityMapKeys);
ArrayList<String> provinceCityValue = provinceCity.get(provinceCityMapKeys);//得到provinceCity的键对应的值集合
for (int i = 0; i < provinceCityValue.size(); i++) {
System.out.println(" "+provinceCityValue.get(i));//循环输出provinceCity的值
}
}
}

}
}