# HashMap collection - traversal methods
Define good collection:
public static void main(String[] args) { Map<String,String> onemap=new HashMap<String,String>(); map.put("1", "value1"); map.put("2", "value2"); map.put("3", "value3"); map.put("4", "value4");
(1) The first: Recommended, especially when a large capacity (highly recommended)
System.out.println("\n通过Map.entrySet遍历key和value"); for(Map.Entry<String, String> entry: onemap.entrySet()) { System.out.println("Key: "+ entry.getKey()+ " Value: "+entry.getValue()); }
(2) The second method
System.out.println("\n通过Map.entrySet使用iterator遍历key和value: "); Iterator map1it=onemap.entrySet().iterator(); while(emap1it.hasNext()) { Map.Entry<String, String> entry=(Entry<String, String>) map1it.next(); System.out.println("Key: "+entry.getKey()+" Value: "+entry.getValue()); } ```
(3) Third: general use, secondary value
System.out.println("\n通过Map.keySet遍历key和value:"); for(String key: onemap.keySet()) { System.out.println("Key: "+key+" Value: "+ onemap.get(key)); }
(4) The fourth
System.out.println ( "\ n traversed by Map.values () all value, but can not traverse the Key" ); for (String V: onemap.values ()) { System.out.println ( "value of The IS" + V); }
(1) by traversing Map.entrySet key value and output:
Key: 1 Value: value1 Key: 2 Value: value2 Key: 3 Value: value3 Key: 4 Value: value4
(2) using the key value and traversing through Map.entrySet iterator 's output :
Key: 1 Value: value1 Key: 2 Value: value2 Key: 3 Value: value3 Key: 4 Value: value4
(3) traversing the key and value output by Map.keySet:
Key: 1 Value: value1 Key: 2 Value: value2 Key: 3 Value: value3 Key: 4 Value: value4
(4) Map.values () through all value, but can not traverse the output of the key:
The value is value1
The value is value2
The value is value3
The value is value4
I hope you can help us with any questions can comment, time for you to solve.