集合嵌套

2023-05-06 16:31:19 浏览数 (3)

看了学习视频,来一段代码

代码语言:javascript复制
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class jiheqiantao {
    public static void main(String[] args) {
        HashMap<String, String> javase = new HashMap<String, String>(); // 基础班
        HashMap<String, String> javaee = new HashMap<String, String>(); // 就业班
        
        javase.put("001", "张三");
        javase.put("002", "李四");
        
        javaee.put("001", "王五");
        javaee.put("002", "赵六");
        
        HashMap<String, HashMap<String, String>> czbk = 
                new HashMap<String, HashMap<String, String>>();
        czbk.put("基础班", javase); // 基础班对应一个HashMap集合
        czbk.put("就业班", javaee); // 就业班对应一个HashMap集合
        keySet(czbk);
        entrySet(czbk);
    }
    // 利用entrySet遍历,效率比keySet要高
    public static void entrySet(HashMap<String, HashMap<String, String>> czbk) {
        Set<Map.Entry<String, HashMap<String, String>>> classNameSet = 
                czbk.entrySet();
        Iterator<Map.Entry<String, HashMap<String, String>>> classNameIt = 
                classNameSet.iterator();
        while (classNameIt.hasNext()) {
            Map.Entry<String, HashMap<String, String>> classNameEntry = 
                    classNameIt.next();
            String classNameKey = classNameEntry.getKey();
            HashMap<String, String> classMap = classNameEntry.getValue();
            Set<Map.Entry<String, String>> studentSet = classMap.entrySet();
            Iterator<Map.Entry<String, String>> studentIt = studentSet.iterator();
            
            
            while (studentIt.hasNext()) {
                Map.Entry<String, String> studentEntry =
                        studentIt.next();
                String numKey = studentEntry.getKey();
                String nameValue = studentEntry.getValue();
                System.out.println(classNameKey   "..."   numKey   "..."   nameValue);
            }
        }
    }
    
    
    
    public static void keySet(HashMap<String, HashMap<String, String>> czbk) {
        Set<String> classNameSet = czbk.keySet();
        Iterator<String> classNameIt = classNameSet.iterator();
        while (classNameIt.hasNext()) {
            String classNameKey = classNameIt.next();
            HashMap<String, String> classMap = czbk.get(classNameKey);
            Set<String> studentNum = classMap.keySet();
            Iterator<String> studentIt = studentNum.iterator();
            while (studentIt.hasNext()) {
                String numKey = studentIt.next();
                String nameValue = classMap.get(numKey);
                System.out.println(classNameKey   "..."   numKey   "..."   nameValue);
            }
        }
    }
}
 

1 人点赞