{"id":2460,"date":"2016-04-15T07:53:44","date_gmt":"2016-04-15T11:53:44","guid":{"rendered":"http:\/\/springframework.guru\/?p=2460"},"modified":"2019-06-16T07:56:19","modified_gmt":"2019-06-16T11:56:19","slug":"iterating-java-map-entries","status":"publish","type":"post","link":"https:\/\/springframework.guru\/iterating-java-map-entries\/","title":{"rendered":"Iterating Java Map Entries"},"content":{"rendered":"<p>The majority of the time when you&#8217;re working with Maps in Java, you&#8217;ll be accessing the map values via the key. There are times you need to walk the map like a list. There&#8217;s a number of ways to do this in Java, which have grown over time as the language has evolved.<\/p>\n<p>Let&#8217;s take a closer look at walking over Map entries in Java using JUnit. For the series of examples below, I&#8217;m going to prepare a map for each test like this:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\">Map&lt;Integer, String&gt; map;\r\n\r\n@Before\r\npublic void setup(){\r\n    map = new HashMap&lt;&gt;();\r\n    map.put(1, \"Java\");\r\n    map.put(2, \"Groovy\");\r\n    map.put(3, \"Scala\");\r\n    map.put(4, \"Clojure\");\r\n    map.put(5, \"jRuby\");\r\n}<\/pre>\n<p>This is a simple <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">HashMap<\/code> in Java. I&#8217;m using generics to say the Map key is an integer, and the Map value is a String. For this example, I&#8217;m creating a map with some of the various JVM languages.<\/p>\n<h3>Using an Iterator over Map Entries<\/h3>\n<p>If you&#8217;re still stuck using Java 1.4, you might use an Iterator to walk the Map entries. But hopefully, you&#8217;re not still on Java 1.4! But there is plenty of legacy code out there still doing this.<\/p>\n<p>Here is an example of using an Iterator over a\u00a0map. I&#8217;m tossing in the use of Generics, so this code snippet is not Java 1.4 compliant. I&#8217;m also using the older style while loop.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\">@Test\r\npublic void testMapWithIterator() throws Exception {\r\n    List jvmLangs = new ArrayList&lt;&gt;();\r\n\r\n    Iterator iterator = map.entrySet().iterator();\r\n\r\n    while (iterator.hasNext()){\r\n        Map.Entry&lt;Integer, String&gt; entry  = (Map.Entry&lt;Integer, String&gt;) iterator.next();\r\n\r\n        jvmLangs.add(entry.getValue());\r\n    }\r\n\r\n    assert jvmLangs.size() == 5;\r\n}<\/pre>\n<p>You can see is using this technique, I need to do a cast:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\">(Map.Entry&lt;Integer, String&gt;) iterator.next();<\/pre>\n<p>I cringe a little every time I need to do a hard cast like this. It&#8217;s generally a code smell.<\/p>\n<h3>Using For Each over Map Entries<\/h3>\n<p>Java 1.5 gave us for each loops. A much nicer syntax for doing loop operations. Here is an example of using a for each loop over Map entries.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\">    @Test\r\n    public void testMapIteration(){\r\n        List jvmLangs = new ArrayList&lt;&gt;();\r\n\r\n        for (Map.Entry&lt;Integer, String&gt; entry : map.entrySet()){\r\n            jvmLangs.add(entry.getValue());\r\n        }\r\n\r\n        assert jvmLangs.size() == 5;\r\n    }<\/pre>\n<p>You can see the code is a little cleaner now. Also gone now is the cast, so this code smells better!<\/p>\n<h3>Using Java 8&#8217;s forEach over Map Entries<\/h3>\n<p>While the Java 7 release was rather boring for developers, Java 8 has brought us some really nice features to work with. We have a new <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">forEach<\/code> statement we can use in conjunction with lambdas. Here is an example of using Java 8 lambdas to iterate over Map entries.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\">@Test\r\npublic void testMapIteration() {\r\n    List langs = new ArrayList&lt;&gt;();\r\n\r\n    map.forEach((k, v) -&gt; langs.add(v));\r\n\r\n    assert langs.size() == 5;\r\n}<\/pre>\n<p>You can see Java 8 really allows us to clean up the code. No casts here. You can also see we&#8217;re skipping over explicitly dealing with the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">Map.Entry<\/code> object in the lambda. Even though we&#8217;re taking a shortcut here, we still have the type safety of Java.<\/p>\n<h2>Conclusion<\/h2>\n<p>I given you 3 different ways of walking over a list of map entries in Java. In my examples here you can see how the code has become cleaner as the Java programming language has evolved over the years.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>The majority of the time when you&#8217;re working with Maps in Java, you&#8217;ll be accessing the map values via the key. There are times you need to walk the map like a list. There&#8217;s a number of ways to do this in Java, which have grown over time as the language has evolved. Let&#8217;s take [&hellip;]<a href=\"https:\/\/springframework.guru\/iterating-java-map-entries\/\" class=\"df-link-excerpt\">Continue reading<\/a><\/p>\n","protected":false},"author":1,"featured_media":4592,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_lmt_disableupdate":"","_lmt_disable":"","_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"_uf_show_specific_survey":0,"_uf_disable_surveys":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"Iterating Java Map Entries #java","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":true,"jetpack_social_options":{"image_generator_settings":{"template":"highway","enabled":false},"version":2}},"categories":[20],"tags":[165,164],"class_list":["post-2460","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-java","tag-java-8","tag-map"],"jetpack_publicize_connections":[],"aioseo_notices":[],"modified_by":"Simanta","jetpack_sharing_enabled":true,"jetpack_featured_media_url":"https:\/\/springframework.guru\/wp-content\/uploads\/2015\/03\/Banner560x292_07web.jpg","jetpack_shortlink":"https:\/\/wp.me\/p5BZrZ-DG","_links":{"self":[{"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/posts\/2460"}],"collection":[{"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/comments?post=2460"}],"version-history":[{"count":8,"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/posts\/2460\/revisions"}],"predecessor-version":[{"id":5602,"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/posts\/2460\/revisions\/5602"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/media\/4592"}],"wp:attachment":[{"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/media?parent=2460"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/categories?post=2460"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/tags?post=2460"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}