Java HashMap 集合操作示例:存储老师和课程信息
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() + '位老师授课');
}
}
}
原文地址: https://www.cveoy.top/t/topic/n632 著作权归作者所有。请勿转载和采集!