Three ways to Traverse 1.keySet () 2.values () 3.entrySet () for map
Three ways to get set, you can use foreach or iterator, you cannot use for, because the data structure determines the
Packagecom.fync.jsj.mapTemplate;Importjava.util.Collection;ImportJava.util.HashMap;ImportJava.util.Map;ImportJava.util.Map.Entry;ImportJava.util.Set;ImportOrg.junit.Before;Importorg.junit.Test; Public classmapcycle {Map<integer, string>map; //get the data ready.@Before Public voidTestData () {map=NewHashmap<>(); Map.put (1, "Zhang San"); Map.put (2, "John Doe"); Map.put (3, "Harry"); Map.put (4, "Leper"); Map.put (5, "Chen Liu"); }/**Test Three ways, these three methods are finally traversing set, so you can use * foreach or iterator
**/ //mode 1:keyset () method gets to set (key)@Test Public voidTestfirst () {Set<Integer> set =Map.keyset (); for(integer integer:set) {System. Out.println (Map.get (integer)); } } //mode 2:values () method gets to collection (value)@Test Public voidTestsecond () {Collection<String> collection =map.values (); for(String string:collection) {System. OUT.PRINTLN (String); } } //mode 3:entryset () method gets to Set<entry<key,value>>@Test Public voidTestthird () {Set<entry<integer, string>> entries =Map.entryset (); for(Entry<integer, string>entry:entries) {System. Out.println (Entry.getvalue ()); } } }
Three ways to traverse map