有两种方法
public static void test4(){
Map map = new HashMap<>();
map.put("key1",1);
map.put("key2",2);
//第一种keySet()
System.out.println("map.keySet():"+map.keySet());
Set strings = map.keySet();
Iterator iterator = map.keySet().iterator();
while (iterator.hasNext()){
System.out.println("iterator:"+iterator.next());
}
//第二种
System.out.println("map.entrySet():"+map.entrySet());
Iterator> iterator1 = map.entrySet().iterator();
while (iterator1.hasNext()){
System.out.println("iterator1:"+iterator1.next());
}
//----------
for (Map.Entry entry : map.entrySet()){
System.out.println("key:"+entry.getKey()+";value:"+entry.getValue());
}
}
打印结果如下: