public class HashMapDemo {
public static void main(String[] args) {
// 创建一个hashmap
HashMap<String, String> map = new HashMap<String, String>();
map.put("张三", "25");
map.put("李四", "26");
map.put("王五", "27");
map.put("麻子", "28");
// 第一种:普通使用,二次取值, 推荐常用掌握*****
System.out.println("\n通过Map.keySet遍历key和value:");
for (String key : map.keySet()) {
System.out.println("Key: " + key + " Value: " + map.get(key));
}
// 第二种
System.out.println("\n通过Map.entrySet使用iterator遍历key和value: ");
Iterator map1it = map.entrySet().iterator();
while (map1it.hasNext()) {
Map.Entry<String, String> entry = (Entry<String, String>) map1it
.next();
System.out.println("Key: " + entry.getKey() + " Value: "
+ entry.getValue());
}
// 第三种:推荐,尤其是容量大时 推荐常用掌握*****
System.out.println("\n通过Map.entrySet遍历key和value");
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println("Key: " + entry.getKey() + " Value: "
+ entry.getValue());
}
// 第四种 ,这种的话不推荐使用
System.out.println("\n通过Map.values()遍历所有的value,但不能遍历key");
for (String v : map.values()) {
System.out.println("The value is " + v);
}
}
public static void main(String[] args) {
// 创建一个hashmap
HashMap<String, String> map = new HashMap<String, String>();
map.put("张三", "25");
map.put("李四", "26");
map.put("王五", "27");
map.put("麻子", "28");
// 第一种:普通使用,二次取值, 推荐常用掌握*****
System.out.println("\n通过Map.keySet遍历key和value:");
for (String key : map.keySet()) {
System.out.println("Key: " + key + " Value: " + map.get(key));
}
// 第二种
System.out.println("\n通过Map.entrySet使用iterator遍历key和value: ");
Iterator map1it = map.entrySet().iterator();
while (map1it.hasNext()) {
Map.Entry<String, String> entry = (Entry<String, String>) map1it
.next();
System.out.println("Key: " + entry.getKey() + " Value: "
+ entry.getValue());
}
// 第三种:推荐,尤其是容量大时 推荐常用掌握*****
System.out.println("\n通过Map.entrySet遍历key和value");
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println("Key: " + entry.getKey() + " Value: "
+ entry.getValue());
}
// 第四种 ,这种的话不推荐使用
System.out.println("\n通过Map.values()遍历所有的value,但不能遍历key");
for (String v : map.values()) {
System.out.println("The value is " + v);
}
}