1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| 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"); map.put("4", "value4"); System.out.println("\n通过Map.keySet遍历key和value:"); for(String key:map.keySet()) { System.out.println("Key: "+key+" Value: "+map.get(key)); } System.out.println("\n通过Map.entrySet使用iterator遍历key和value: "); Iterator map1it=map.entrySet().iterator(); while(map1it.hasNext()) { Map.Entry<String, String> entry=(Entry<String, String>) map1it.next(); System.out.println("Key: "+entry.getKey()+" Value: "+entry.getValue()); } System.out.println("\n通过Map.entrySet遍历key和value"); for(Map.Entry<String, String> entry: map.entrySet()) { System.out.println("Key: "+ entry.getKey()+ " Value: "+entry.getValue()); } System.out.println("\n通过Map.values()遍历所有的value,但不能遍历key"); for(String v:map.values()) { System.out.println("The value is "+v); } }
|