public static void test1(){
Iterator<Map.Entry<String,String>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String , String > entry = iterator.next();
String key = entry.getKey();
String value = entry.getValue();
System.out.println(key);
System.out.println(key+":"+value);
}
}
public static void test2(){
for (Map.Entry<String,String> entry : map.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
System.out.println(key);
System.out.println(key+":"+value);
}
}
public static void test3(){
for (String key : map.keySet()) {
System.out.println(key);
}
}
public static void test4(){
for (String value : map.values()) {
System.out.println(value);
}
}
static Map<String , String > map = new HashMap<>();
public static void main(String[] args) {
map.put("name","张三");
map.put("age","21");
map.put("sex","男");
System.out.println("使用迭代器遍历map的键值对结果如下所示:");
test1();
System.out.println("使用for-each循环遍历Map的键值对:");
test2();
System.out.println("只遍历Map的键结果如下所示:");
test3();
System.out.println("只遍历Map的值结果如下所示:");
test4();
}
输出如下所示:
使用迭代器遍历map的键值对结果如下所示:
sex
sex:男
name
name:张三
age
age:21
使用for-each循环遍历Map的键值对:
sex
sex:男
name
name:张三
age
age:21
只遍历Map的键结果如下所示:
sex
name
age
只遍历Map的值结果如下所示:
男
张三
21