package com.soar.map;
import java.util.HashMap;
import com.soar.bean.Student;
public class Demo8_HashMapHashMap {
/*
* * A:案例演示
* 集合嵌套之HashMap嵌套HashMap
*
* 需求:
* 一班键是学生,值是学生的归属地
* 二班键是学生,值是学生的归属地
*
* 将班级对象添加到双列集合中
*/
public static void main(String[] args) {
//定义一班
HashMap<Student,String> hm1 = new HashMap<>();
hm1.put(new Student("张三",23),"北京");
hm1.put(new Student("李四",24),"北京");
hm1.put(new Student("王五",25),"上海");
hm1.put(new Student("赵六",26),"广州");
//定义二班
HashMap<Student,String> hm2 = new HashMap<>();
hm2.put(new Student("唐僧",123),"北京");
hm2.put(new Student("孙悟空",1024),"北京");
hm2.put(new Student("猪八戒",1025),"上海");
hm2.put(new Student("沙和尚",269),"广州");
//定义大集合
HashMap<HashMap<Student,String>,String> hm = new HashMap<>();
hm.put(hm1, "一班");
hm.put(hm2, "二班");
//遍历双列集合
for (HashMap<Student,String> h : hm.keySet()) { //hm.keySet()代表的是双列集合中键的集合
String value = hm.get(h); //get(h)根据键对象获取值对象
//遍历键的双列集合对象
for (Student key : h.keySet()) { //h.keySet()获取集合中所有的学生键对象
String value2 = h.get(key);
System.out.println(key + "=" + value2 + value);
/*
Student [name=孙悟空, age=1024]=北京二班
Student [name=猪八戒, age=1025]=上海二班
Student [name=沙和尚, age=269]=广州二班
Student [name=唐僧, age=123]=北京二班
Student [name=张三, age=23]=北京一班
Student [name=李四, age=24]=北京一班
Student [name=王五, age=25]=上海一班
Student [name=赵六, age=26]=广州一班
*/
}
}
}
}
Java_基础—集合嵌套之HashMap嵌套HashMap
最新推荐文章于 2023-02-28 23:01:04 发布