package cn.zmh.zuoye; import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/*
* 定义
* aaa学校
* 定义两个班级
* java班 学号,姓名
* 001 张三1
* 002 张三2
* hdoop班 学号,姓名
* 001 张三3
* 002 张三4
* */
public class MapDemo1 {
public static void main(String[] args) {
Map<String,String> javas = new HashMap<>();
Map<String,String> hdoop = new HashMap<>();
// 键值不能重复
javas.put("","张三1");
javas.put("","张三2");
hdoop.put("","张三3");
hdoop.put("","张三4");
Map<String,Map<String,String>> aaa = new HashMap<>();
aaa.put("java班",javas);
aaa.put("hdoop班",hdoop);
//调用方法 传参
fun1(aaa);
}
//第一种 迭代器 Iterator entrySet();
public static void fun1(Map<String, Map<String, String>> aaa) {
Set<Map.Entry<String,Map<String,String>>> classNameSet = aaa.entrySet();
Iterator<Map.Entry<String,Map<String,String>>> it = classNameSet.iterator();
while(it.hasNext()){
Map.Entry<String, Map<String, String>> next = it.next();
String classNamekey = next.getKey();
Map<String, String> classNameValue = next.getValue();
System.out.println(classNamekey);
Set<Map.Entry<String, String>> studentSet = classNameValue.entrySet();
Iterator<Map.Entry<String,String>> studendIt = studentSet.iterator();
while (studendIt.hasNext()){
Map.Entry<String, String> next1 = studendIt.next();
String studentkey = next1.getKey();
String studendValue = next1.getValue();
System.out.println("\t"+studentkey+":"+studendValue);
}
}
}
//第二种 增强for循环 entrySet();
public static void fun2(Map<String, Map<String, String>> aaa) {
Set<Map.Entry<String, Map<String, String>>> classNameSet = aaa.entrySet();
for(Map.Entry<String,Map<String,String>> i:classNameSet){
String classNamekey = i.getKey();
Map<String, String> classNameValue = i.getValue();
System.out.println(classNamekey);
Set<Map.Entry<String, String>> studentSet = classNameValue.entrySet();
for(Map.Entry<String, String> i1:studentSet){
String studentkey = i1.getKey();
String studentValue = i1.getValue();
System.out.println("\t"+studentkey+":"+studentValue);
}
}
}
//第三种 迭代器 Iterator 方法keySet();
public static void fun3(Map<String, Map<String, String>> aaa) {
Set<String> classNameSet = aaa.keySet();
Iterator<String> it = classNameSet.iterator();
while (it.hasNext()){
String classNameKey = it.next();
Map<String, String> classNameValue = aaa.get(classNameKey);
System.out.println(classNameKey);
//System.out.println(classNameValue);
Set<String> studentSet = classNameValue.keySet();
Iterator<String> it1 = studentSet.iterator();
while (it1.hasNext()){
String studentKey = it1.next();
//System.out.println(studentKey);
String studentValue = classNameValue.get(studentKey);
System.out.println(studentKey+":"+studentValue);
}
}
}
}
打印结果