📄 mapdemo.java
字号:
package chapter9;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
public class MapDemo {
public static void main(String[] args) {
HashMap<String, String> mapHash = new HashMap<String, String>();
// 使用put方法添加键值对HashMap对象
mapHash.put("one", "ABC");
mapHash.put("two", "DEF");
mapHash.put("three", "GHI");
mapHash.put("four", "JKL");
mapHash.put("five", "MNO");
mapHash.put("six", "PQR");
mapHash.put("seven", "STU");
// 使用get方法通过键获取值的方法
String query = "six";
System.out.println("the key at " + query + ".");
String resultString = (String) mapHash.get(query);
System.out.println("the value: " + resultString + "\n");
// 通过keySet方法获取键集合
Set setKey = mapHash.keySet();
System.out.println("setKey = " + setKey);
Collection valueSet = mapHash.values();
System.out.println("valueSet = " + valueSet);
// 一次性输出HashMap对象中的所有键值
Iterator iter = mapHash.keySet().iterator();
while (iter.hasNext()) {
String key = (String) iter.next();
System.out.println("Key " + key + "; Value "
+ (String) mapHash.get(key));
}
// 通过entrySet方法获取Set视图
Set<Entry<String, String>> hsm = mapHash.entrySet();
Iterator<Entry<String, String>> i = hsm.iterator();
for (; i.hasNext();) {
Entry en = i.next();
System.out.println("the key is " + en.getKey()
+ " || the value is " + en.getValue());
}
// 使用size方法
System.out.println("the size is :" + hsm.size());
System.out.println("the size of the Hashmap is :" + mapHash.size());
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -