版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/cnd2449294059/article/details/81661402
package com.cnd05;
import java.util.HashMap;
import java.util.Set;
//HashMap嵌套HashMap结构
public class TreeMapDemo2 {
public static void main(String[] args) {
//创建集合
HashMap<String,HashMap<String,Integer>> sumMap=new HashMap<String,HashMap<String,Integer>>();
//先存储元素,后遍历元素
HashMap<String,Integer> hm1=new HashMap<String,Integer>();
hm1.put("高跃", 22);
hm1.put("李杰", 20);
HashMap<String,Integer> hm2=new HashMap<String,Integer>();
hm2.put("方乐", 24);
hm2.put("贾芳", 23);
//存储元素
sumMap.put("一年级", hm1);
sumMap.put("二年级", hm2);
//遍历元素
Set<String> sumMapSet=sumMap.keySet();
for(String key:sumMapSet) {
System.out.println(key);
HashMap<String,Integer> subMapValue=sumMap.get(key);
//遍历键值(HashMap结构)
Set<String> subMapValueSet = subMapValue.keySet();
for(String key2:subMapValueSet) {
Integer subMapValueSetValue=subMapValue.get(key2);
System.out.println("\t"+key2+"---"+subMapValueSetValue);
}
}
}
}
运行结果为:
一年级
高跃---22
李杰---20
二年级
贾芳---23
方乐---24