Copy Code code as follows:
public static void Main (String args[]) {
map<string, object> map = new hashmap<string, object> ();
Map.put ("A", "a");
Map.put ("B", "B");
Map.put ("C", "C");
Keyset traversal
Iterator<string> iterator = Map.keyset (). iterator ();
while (Iterator.hasnext ()) {
String key = Iterator.next ();
String value = (string) map.get (key);
System.out.println (value);
}
For (String Key:map.keySet ()) {
String value = (string) map.get (key);
System.out.println (value);
}
EntrySet traversal
iterator<entry<string, object>> Iterator1 = Map.entryset (). iterator ();
while (Iterator1.hasnext ()) {
String value = (string) iterator1.next (). GetValue ();
System.out.println (value);
}
For (entry<string, object> entry:map.entrySet ()) {
String value = (string) entry.getvalue ();
System.out.println (value);
}
//
For (Object str:map.values ()) {
System.out.println (str);
}
}
On the question of efficiency:
If you use HashMap
While traversing key and value, the performance difference between keyset and entryset depends on the specific conditions of the key, such as complexity (complex object), divergence, conflict rate and so on. In other words, it depends on the cost of HashMap to find value. EntrySet a one-time removal of all keys and value of the operation is a performance cost, when this loss is less than HashMap to find the cost of value, EntrySet performance advantage will be reflected. For example, when key is the simplest numeric string in the comparison test, keyset may be more efficient and time-consuming than entryset 10% less. Generally speaking, it is recommended to use EntrySet. Because when key is very simple, its performance may be slightly lower than keyset, but it is controllable, and with the complexity of key, EntrySet advantage will be obvious. Of course, we can choose according to the actual situation
The keyset method is more appropriate when only the key is traversed, because the entryset takes out the useless value, wasting performance and space. In the above test results, keyset is 23% less time-consuming than the EntrySet method.
Using the Vlaues method is the best choice when traversing value only, EntrySet is slightly better than the keyset method.
If you use TreeMap
While traversing key and value, the performance of EntrySet is much higher than that of keyset, unlike HashMap. This is determined by the query efficiency of TREEMAP, that is, the TreeMap to find value is significantly higher than the cost of EntrySet to remove all keys and value at once. Therefore, it is strongly recommended to use the EntrySet method when traversing TreeMap.