There are several ways to map traversal in Java, from the earliest iterator to the Java5-supported foreach to the Java8 Lambda, let's take a look at the specific usage and the pros and cons of each.
Initialize a map First:
Public class TestMap { publicstaticnew Hashmap<integer, integer>();}
KeySet values
If you only need map key or value, using the map's keyset or values method is undoubtedly the most convenient
//KeySet Get key Public voidTestkeyset () { for(Integer key: map.keyset ()) {System. out. println (key); } } //values Get value Public voidtestvalues () { for(Integer value: map.values ()) {System. out. println (value); } }
KeySet Get (Key)
If you need to get both key and value, you can get the key first, and then get the value from the map's get (key). (It should be stated that this method is not an optimal choice, generally not recommended)
// KeySet Get (key) get key and value Public void Testkeysetandgetkey () { formap.keyset ()) { System. out " : " Map.get (key)); } }
EntrySet
entryset traversal for map , You can also get key and value at the same time, in general, performance is better than the previous one, which is also most commonly used traversal method
// EntrySet get key and value Public void Testentry () { for (Map.entry<integer, integer> entry:map.entrySet () ) { System. out. println (entry.getkey () + ":" + entry.getvalue ()); } }
Iterator
For the above several kinds of foreach can be replaced with iterator, in fact, foreach is supported in Java5, the wording of foreach looks more concise, but iterator also has its advantages: when using foreach to traverse the map, If you change its size, you will get an error, but if you just delete the element, you can use the iterator Remove method to delete the element.
//Iterator EntrySet get key and value Public voidTestiterator () { Iterator <map.entry<integer, integer>> it = Map.entryset (). iterator (); while(It.hasnext ()) { map.entry <integer, integer> entry = It.next (); System. out. println (Entry.getkey () +":"+Entry.getvalue ()); //it.remove (); Delete element } }
Lambda
JAVA8 provides lambda expression support, syntax looks more concise, can get key and value at the same time, but tested, performance is less than entryset, so it is recommended to use the EntrySet way
// Lambda gets key and value Public void Testlambda () { System. out " : " + value); });
Summarize
If you just get key, or value, it is recommended to use keyset or the values method
If you need both key and value, use EntrySet
If you need to remove an element during traversal, it is recommended to use iterator
If you need to add elements during the traversal, you can create a new temporary map to hold the new elements, wait for the traversal to complete, and then place the temporary map in the original map.
Several methods of traversing map in Java