map集合被使用是因为具备映射关系。
一个学校有多个教室,每个教室都有多个学生。
public class Demo { public static void main(String[] args) { HashMap<String,HashMap<String,String>> czbk = new HashMap<String,HashMap<String,String>>(); HashMap<String,String> yure = new HashMap<String,String>(); yure.put("01","xiaoming"); yure.put("02","xiaohong"); HashMap<String,String> jiuye = new HashMap<String,String>(); jiuye.put("01","xiaoxue"); jiuye.put("02","xiaoli"); czbk.put("jiuyeban",jiuye); czbk.put("yureban",yure); getInfo(czbk); } public static void getStudentInfo(HashMap<String ,String> roomMap){ Iterator<String> it = roomMap.keySet().iterator(); while (it.hasNext()){ String id = it.next(); String name = roomMap.get(id); System.out.println(id+":"+name); } } public static void getInfo(HashMap<String,HashMap<String,String>> school){ Iterator<String> it = school.keySet().iterator(); while (it.hasNext()){ String roomName = it.next(); HashMap<String,String> room = school.get(roomName); System.out.println(roomName); getStudentInfo(room); } } }
class Student { private int id; private String name; public Student(int id, String name) { this.id = id; this.name = name; } @Override public String toString() { return "Student{" + "id=" + id + ", name=‘" + name + ‘\‘‘ + ‘}‘; } } public class Demo { public static void main(String[] args) { HashMap<String, List<Student>> czbk = new HashMap<String, List<Student>>(); List<Student> yure = new ArrayList<Student>(); List<Student> jiuye = new ArrayList<Student>(); czbk.put("yureban", yure); czbk.put("jiuyeban", jiuye); yure.add(new Student(1, "xiaohong")); yure.add(new Student(2, "xiaoli")); jiuye.add(new Student(1, "xiaoxue")); jiuye.add(new Student(2, "xiaomeng")); Iterator<String> it = czbk.keySet().iterator(); while (it.hasNext()) { String roomName = it.next(); List<Student> room = czbk.get(roomName); System.out.println(roomName); getInfos(room); } } public static void getInfos(List<Student> room) { Iterator<Student> it = room.iterator(); while (it.hasNext()) { System.out.println(it.next()); } } }
原文地址:https://www.cnblogs.com/hongxiao2020/p/12661300.html
时间: 2024-11-09 10:44:24