我们创建两个HashMap集合,并且向里面扔几个自定义对象类型的元素进去,之后我们把两个HashMap集合放到另一个HashMap集合中去,作为大的HashMap集合的键值对中的键,其值还是一个String类型的字符串。接下来我们就要去循环遍历它,先用keySet()方法获取到最外层的HashMap的键,就是内层的两个HashMap,其类型为:HashMap<Student, String>,拿到它我们就可以非常容易地keySet()方法再次得到最内层的student的键,然后通过get()方法获取其value值啦!
import java.util.HashMap;
import com.heima.bean.Student;
public class Demo7_HashMapHashMap {
public static void main(String[] args) {
HashMap<Student,String> hm88 = new HashMap<>();
hm88.put(new Student("张三", 23), "北京");
hm88.put(new Student("李四", 24), "北京");
hm88.put(new Student("赵六", 26), "上海");
hm88.put(new Student("王五", 28), "深圳");
HashMap<Student,String> hm99 = new HashMap<>();
hm99.put(new Student("孙悟空", 2000), "花果山");
hm99.put(new Student("猪八戒", 1500), "高老庄");
hm99.put(new Student("沙悟净", 1600), "流沙河");
hm99.put(new Student("唐三藏", 1003), "长安");
HashMap<HashMap<Student,String>,String> hm = new HashMap<>();
hm.put(hm88, "88期");
hm.put(hm99, "99期");
for (HashMap<Student, String> stu : hm.keySet()) {
String value = hm.get(stu);
System.out.println(value);
for (Student key : stu.keySet()) { //获取集合中所有的学生
System.out.println(key + " " + stu.get(key));
}
}
}
}
运行结果:
88期
Student [name=王五, age=28] 深圳
Student [name=张三, age=23] 北京
Student [name=李四, age=24] 北京
Student [name=赵六, age=26] 上海
99期
Student [name=孙悟空, age=2000] 花果山
Student [name=唐三藏, age=1003] 长安
Student [name=猪八戒, age=1500] 高老庄
Student [name=沙悟净, age=1600] 流沙河