package itcast05;
import java.util.HashMap;
import java.util.Set;
/**
* HashMap嵌套HashMap
*
* @author lgt
*
*/
public class HashMapDemo {
public static void main(String[] args) {
// 创建集合对象
HashMap<String, HashMap<String, Integer>> czbkMap = new HashMap<String, HashMap<String, Integer>>();
// 创建基础班jc集合对象
HashMap<String, Integer> jcMap = new HashMap<String, Integer>();
// 添加元素
jcMap.put("石乐志", 22);
jcMap.put("芜湖大司马", 39);
// 把基础班jcMap添加到czbkMap集合中
czbkMap.put("jc", jcMap);
// 创建就业班jy集合对象
HashMap<String, Integer> jyMap = new HashMap<String, Integer>();
// 添加元素
jyMap.put("怎么说", 28);
jyMap.put("不存在的", 12);
// 把基础班jyMap添加到czbkMap集合中
czbkMap.put("jy", jyMap);
// 遍历czbkMap集合方式1 根据键查找值
// 获取所有的键
Set<String> czbkMapSet = czbkMap.keySet();
// 遍历键的集合,获取每一个键
for (String czbkMapKey : czbkMapSet) {
System.out.println("班级类型:" + czbkMapKey);
// 根据键查找值
HashMap<String, Integer> czbkMapValue = czbkMap.get(czbkMapKey);
// 获取所有的键jcMap,jyMap
Set<String> jxMapSet = czbkMapValue.keySet();
for (String jxMapSetKey : jxMapSet) {
// 根据键查找值
int age = czbkMapValue.get(jxMapSetKey);
// System.out.println("班级类型:" + czbkMapKey + ", 姓名:" +
// jxMapSetKey + ", 年龄:" + age);
System.out.println("\t\t" + "姓名:" + jxMapSetKey + ", 年龄:" + age);
}
}
}
}
package itcast05;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;
/**
* ArrayList集合嵌套HashMap集合并遍历
*
* @author lgt
*
*/
public class HashMapIncludeArrayListDemo {
public static void main(String[] args) {
// 创建集合对象
ArrayList<HashMap<String, String>> array = new ArrayList<HashMap<String, String>>();
// 创建元素1
HashMap<String, String> hm1 = new HashMap<String, String>();
hm1.put("周瑜", "小乔");
hm1.put("吕布", "貂蝉");
// 把元素添加到array里面
array.add(hm1);
// 创建元素2
HashMap<String, String> hm2 = new HashMap<String, String>();
hm2.put("郭靖", "黄蓉");
hm2.put("杨过", "小龙女");
// 把元素添加到array里面
array.add(hm2);
// 创建元素3
HashMap<String, String> hm3 = new HashMap<String, String>();
hm3.put("令狐冲", "任盈盈");
hm3.put("林平之", "岳灵珊");
// 把元素添加到array里面
array.add(hm3);
// 遍历
for (HashMap<String, String> hm : array) {
Set<String> set = hm.keySet();
for (String key : set) {
String value = hm.get(key);
System.out.println(key + "---" + value);
}
}
}
}
因篇幅问题不能全部显示,请点此查看更多更全内容