1. Basic overview
Set < Map.entry < K , V >> entryset() returns a set view of the mappings included in this map.
Set < K > keySet() returns a set view of the keys included in this map.
2. Efficiency analysis
For keyset in fact it is traversed 2 times, one is converted to iterator. Remove the value of key from the HashMap one time.
and EntrySet just traversed for the first time, he put the key and value in the entry, so it's fast.
3. Use Example
Map<string, string> maps = new hashmap<string, string> ();
Method one: With EntrySet ()
Iterator<entry<string,string>> it = Maps.entryset (). Iterator ();
while (It.hasnext ()) {
map.entry<string,string> m = It.next ();
String key = M.getkey ();
String value= M.getvalue ();
}
Method Two: jdk1.5 support, with EntrySet () and For-each loops ()
For (map.entry<string, string> m:maps.entryset ()) {
String key = M.getkey ();
String value= M.getvalue ();
}
Method Three: With Keyset ()
Iterator<string> it2 = Maps.keyset (). Iterator ();
while (It2.hasnext ()) {
String key = It2.next ();
String value= Maps.get (key);
}
Method Four: jdk1.5 support. Cycle with keyset () and For-each
For (String M:maps.keyset ()) {
String key = m;
String value= Maps.get (m);
}
The efficiency of the foreach and while is almost identical, and for is relatively slow.
foreach It can replace the for right? Obviously not.
foreach internal in principle or actually Iterator. But it cannot be artificially controlled like iterator, and it cannot be called iterator.remove (), but you cannot use indexes to facilitate access to components.
So this cycle of foreach is generally only suitable for iterations, extracting data display, and not suitable for adding complex operations based on criteria, such as deletion and use.
Keyset and EntrySet