All in java implement map Map interface, so all Map (eg HashMap, TreeMap, LinkedHashMap, Hashtable, etc.) can be used in the following manner to traverse.
- Method a: Map traversal using entries in a for loop:
/ **
* The most common and most used in most cases, generally require the use of key-value pairs
* /
the Map <String, String> = new new HashMap the Map <String, String> ();
map.put ( "Bear large "," brown ");
map.put (" bears two "," yellow ");
for (of Map.Entry <String, String> entry: EnumMap.entrySet ()) {
String MapKey entry.getKey = ();
entry.getValue mapValue = String ();
System.out.println (MapKey + ":" + mapValue);
}
- Method two: traversing key or values in a for loop, only generally applicable to key in the map, or using the value, the better in performance than entrySet;
Map <String,String>map = new HashMap<String,String>();
map.put("熊大", "棕色");
map.put("熊二", "黄色");
//key
for(String key : map.keySet()){
System.out.println(key);
}
//value
for(String value : map.values()){
System.out.println(value);
}
- Method three: The Iterator traversal;
Iterator<Entry<String, String>> entries = map.entrySet().iterator();
while(entries.hasNext()){
Entry<String, String> entry = entries.next();
String key = entry.getKey();
String value = entry.getValue();
System.out.println(key+":"+value);
}
- Method four: traversing through the key value to find, in this way the efficiency is relatively low, because the operation itself is time-consuming from the key value;
for(String key : map.keySet()){
String value = map.get(key);
System.out.println(key+":"+value);
}