public static void main(string[] args) { map<string, string> map = new hashmap<string, string>(); map.put(1, value1); map.put(2, value2); map.put(3, value3); //第一种:普遍使用,二次取值 system.out.println(通过map.keyset遍历key和value:); for (string key : map.keyset()) { system.out.println(key= + key + and value= + map.get(key)); } //第二种 system.out.println(通过map.entryset使用iterator遍历key和value:); iterator it = map.entryset().iterator(); while (it.hasnext()) { map.entry<string, string> entry = it.next(); system.out.println(key= + entry.getkey() + and value= + entry.getvalue()); } //第三种:推荐,尤其是容量大时 system.out.println(通过map.entryset遍历key和value); for (map.entry<string, string> entry : map.entryset()) { system.out.println(key= + entry.getkey() + and value= + entry.getvalue()); } //第四种 system.out.println(通过map.values()遍历所有的value,但不能遍历key); for (string v : map.values()) { system.out.println(value= + v); } }
以上就是map遍历实例详解的详细内容。