package ListApp.Generics;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class Generics001 {
public static void main(String[] args) {
HashMap<String, Integer> map1 = new HashMap<>();
map1.put("张三",18);
map1.put("李四",12);
System.out.println("初始:"+map1);
System.out.println("转为集合后:"+map1.entrySet());
System.out.println("第一种:使用迭代器遍历");
Iterator<Map.Entry<String, Integer>> iterator = map1.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Integer> map = iterator.next();
System.out.println(map);
}
System.out.println("第二种:使用for遍历map");
for (Map.Entry<String, Integer> map : map1.entrySet()) {
System.out.println(map);
}
System.out.println("第三种:分别遍历出key和value");
for (String s : map1.keySet()) {
System.out.println(s);
}
for (Integer value : map1.values()) {
System.out.println(value);
}
}
}
【JAVA-hashMap3种遍历方式】
于 2022-03-03 20:25:19 首次发布