import java.util.HashMap; import java.util.Map; import java.util.Set;

public class HashMapTest { public static void main(String[] args) { //创建HashMap集合 Map<String, String> teacherMap = new HashMap<>(); //向集合中存储老师和所教课程信息 teacherMap.put("Tom", "CoreJava"); teacherMap.put("John", "Oracle"); teacherMap.put("Susan", "Oracle"); teacherMap.put("Jerry", "JDBC"); teacherMap.put("Jim", "Unix"); teacherMap.put("Kevin", "JSP"); teacherMap.put("Lucy", "JSP");

    //将jim老师的课程修改为Linux
    teacherMap.put("Jim", "Linux");

    //判断有没有Jack老师
    if (teacherMap.containsKey("Jack")) {
        System.out.println("有Jack老师");
    } else {
        System.out.println("无Jack老师");
    }

    //判断有没有HTML课程
    if (teacherMap.containsValue("HTML")) {
        System.out.println("有HTML课程");
    } else {
        System.out.println("无HTML课程");
    }

    //求susan老师教哪门课程
    String course = teacherMap.get("Susan");
    System.out.println("Susan老师教" + course + "课程");

    //求一共有几门不同的课程,一共有几位老师
    Set<String> courseSet = new HashSet<>();
    Set<String> teacherSet = new HashSet<>();
    for (String value : teacherMap.values()) {
        courseSet.add(value);
    }
    for (String key : teacherMap.keySet()) {
        teacherSet.add(key);
    }
    System.out.println("一共有" + courseSet.size() + "门不同的课程");
    System.out.println("一共有" + teacherSet.size() + "位老师");

    //有没有一个老师教多个课程
    Map<String, Integer> courseCount = new HashMap<>();
    for (String value : teacherMap.values()) {
        if (!courseCount.containsKey(value)) {
            courseCount.put(value, 1);
        } else {
            int count = courseCount.get(value);
            courseCount.put(value, count + 1);
        }
    }
    boolean flag = false;
    for (int count : courseCount.values()) {
        if (count > 1) {
            flag = true;
            break;
        }
    }
    if (flag) {
        System.out.println("有老师教多门课程");
    } else {
        System.out.println("没有老师教多门课程");
    }

    //教jsp课程的老师的名字,打印出来
    for (Map.Entry<String, String> entry : teacherMap.entrySet()) {
        if ("JSP".equals(entry.getValue())) {
            System.out.println(entry.getKey() + "教JSP课程");
        }
    }

    //将每门课程的授课老师人数,求出来,存到一个新的Map中
    Map<String, Integer> teacherCount = new HashMap<>();
    for (String value : teacherMap.values()) {
        if (!teacherCount.containsKey(value)) {
            teacherCount.put(value, 1);
        } else {
            int count = teacherCount.get(value);
            teacherCount.put(value, count + 1);
        }
    }
    for (Map.Entry<String, Integer> entry : teacherCount.entrySet()) {
        System.out.println(entry.getKey() + "课程有" + entry.getValue() + "位老师授课");
    }
}
创建一个HashMap集合 1向集合中存储以下老师和所教课程信息 Tom ---- CoreJava John----Oracle Susan----Oracle Jerry----JDBC Jim----Unix Kevin----JSP Lucy----JSP 2 将jim老师的课程修改为Linux 3 判断有没有Jack老师有无 4 判断有没有H

原文地址: https://www.cveoy.top/t/topic/feOm 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录