Package decorator; Import java.util.Collection; Import Java.util.HashMap; Import Java.util.Map; Import Java.util.Map.Entry; Import Java.util.Set; Import Org.junit.Before; Import Org.junit.Test; /** * Three ways for map traversal 1.keySet () 2.values () 3.entrySet () * Three ways to get set, you can use foreach or iterator, cannot use for, because the data structure determines the * * @aut Hor Administrator * * */public class Mapcycle {map<integer, string> Map; Ready data @Before public void TestData () {map = New Hashmap<> (); Map.put (1, "Ling Yi"); Map.put (2, "Ling er"); Map.put (3, "ling three"); Map.put (4, "Ling Si"); Map.put (5, "Ling Five"); }/** Test Three ways, these three methods are finally traversing set, so you can use the foreach or iterator **///Way 1:keyset () method to get to set (key) @Test public void Testfirst () { set<integer> set = Map.keyset (); For (integer integer:set) {System. Out.println (Map.get (integer)); }}//Way 2:values () method gets to collection (value) @Test public void Testsecond () {collection<string& Gt Collection = Map.values (); for (string string:collection) {System. OUT.PRINTLN (String); }}//Mode 3:entryset () method gets to set<entry<key,value& gt;> @Test public void Testthird () {set<e Ntry<integer, string>> entries = Map.entryset (); for (Entry<integer, string> entry:entries) {System. Out.println (Entry.getvalue ( )); } } }
Map three ways to traverse