1 package com.hungteshun; 2 3 import java.util.HashMap; 4 import java.util.Iterator; 5 import java.util.Map; 6 7 /** 8 * @author hungteshun 9 * @description: 10 * @date 2018/11/12 17:53 11 */ 12 public class TestMap { 13 public static void main(String[] args) { 14 Map<Integer, String> map = new HashMap<>(); 15 map.put(1, "张三"); 16 map.put(2, "李四"); 17 map.put(3, "王五"); 18 map.put(4, "王五"); 19 map.put(4, "王五"); 20 System.out.println("map的大小:" + map.size()); 21 22 System.out.println(); 23 System.out.println("方式一:通过Map.keySet遍历key和value:"); 24 for (Integer key : map.keySet()) { 25 String s = map.get(key); 26 System.out.println(key + ": " + s); 27 } 28 System.out.println(); 29 30 System.out.println("方式二:通过Map.entrySet遍历key和value:"); 31 System.out.println("推荐,尤其是容量大时"); 32 for (Map.Entry<Integer, String> entry : map.entrySet()) { 33 System.out.println(entry.getKey() + ": " + entry.getValue()); 34 } 35 System.out.println(); 36 37 System.out.println("方式三:通过Map.entrySet使用iterator遍历key和value:"); 38 Iterator<Map.Entry<Integer, String>> iterator = map.entrySet().iterator(); 39 while (iterator.hasNext()) { 40 Map.Entry<Integer, String> entry = iterator.next(); 41 System.out.println(entry.getKey() + ": " + entry.getValue()); 42 } 43 System.out.println(); 44 45 System.out.println("方式四:通过Map.values()遍历所有的value,但不能遍历key"); 46 for (String value : map.values()) { 47 System.out.println(value); 48 } 49 } 50 }
运行结果:
1 map的大小:4 2 3 方式一:通过Map.keySet遍历key和value: 4 1: 张三 5 2: 李四 6 3: 王五 7 4: 王五 8 9 方式二:通过Map.entrySet遍历key和value: 10 推荐,尤其是容量大时 11 1: 张三 12 2: 李四 13 3: 王五 14 4: 王五 15 16 方式三:通过Map.entrySet使用iterator遍历key和value: 17 1: 张三 18 2: 李四 19 3: 王五 20 4: 王五 21 22 方式四:通过Map.values()遍历所有的value,但不能遍历key 23 张三 24 李四 25 王五 26 王五
原文:https://www.cnblogs.com/blogxu/p/Map.html