Map three ways to traverse

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.