public static void main(String[] args) {
//创建集合对象
Map<String, String> hashMap = new HashMap<>();
//存储数据
hashMap.put(“老师”, “课程”);
hashMap.put(“Tom”, “CoreJava”);
hashMap.put(“John”, “Oracle”);
hashMap.put(“Charles”, “Python”);
hashMap.put(“Jerry”, “PHP”);
hashMap.put(“Jim”, “Unix”);
hashMap.put(“kevin”, “JSP”);
hashMap.put(“Lucy”,“JSP”);
//增加一位新老师Alden教PHP;
hashMap.put(“Alden”,“PHP”);
//lucy改为教Go
Set<Entry<String, String>> entrySet = hashMap.entrySet();
for (Entry<String, String> entry : entrySet) {
String key = entry.getKey();
if (key.equals("Lucy")) {
entry.setValue("Go");
}
}
//方式一:用for集合
for (Entry<String, String> entry : entrySet) {
System.out.println("老师:"+entry.getKey()+"课程:");
}
//方式二:用增强for循环
Set<String> set = hashMap.keySet();
for (String str : set) {
String string = hashMap.get(str);
System.out.println("老师:"+str+"课程:"+string);
}
//方式三:使用迭代器来遍历键的集合
Set<String> keySet = hashMap.keySet();
Iterator<String > iterator = keySet.iterator();
while(iterator.hasNext()) {
String key = iterator.next();
String value = (String)hashMap.get(key);
System.out.println(key+"="+value);
}
//输出所有教PHP的老师;
for (Entry<String, String> entry : entrySet) {
if(entry.getValue().equals("PHP")) {
System.out.println(entry.getKey());
}
}
}
}