Map集合是具有保存映射关系的集合,以健值对的关系存在的。集合里保存这两种值,一种是Key值,另一种是Value值。
Map集合的嵌套是一个集合中嵌套里一个集合,也就是一个集合中有另外一个集合。
我下面写的是在18级找班级和班级的学生姓名和学生年龄。
我用的方法是通过Key值找Value值
package jihe;
import java.util.HashMap;
import java.util.Set;
public class Student {
public String string;
public int age;
public Student(String string, int age) {
this.string = string;
this.age = age;
}
public String toString() {
return " " + string + " " + age+ "";
}
public static void main(String[] args) {
HashMap<String, HashMap<String, Student>> ha = new HashMap<>();//这个集合存放年级和学生信息
HashMap<String, Student> ha1 = new HashMap<>();// 班级,姓名,年龄
Student st1 = new Student("z", 23);
Student st2 = new Student("q", 24);
ha1.put("001", st1);//班级和学生信息
ha1.put("002", st2);班级和学生信息
ha.put("18", ha1);//年级和学生
Set<String> se = ha.keySet();//得到Key
for (String st : se) {
System.out.println(st);
HashMap<String, Student> value = ha.get(st);//通过Key值找Value值(学生信息)
Set<String> se1 = value.keySet();//再通过Value值(学生信息)找班级和学生姓名年龄
for (String str1 : se1) {
Student stu = value.get(str1);
System.out.println(str1 + "...." +stu);//打印键值队
}
}
}
}