<p>If I have an object implementing the <code>Map</code> interface in Java and I wish to iterate over every pair contained within it,  what is the most efficient way of going through the map?</p>

<p>Will the ordering of elements depend on the specific map implementation that I have for the interface?</p>

[{'answer_id': 46905, 'author': 'pkaeding', 'author_id': 4257, 'author_profile': 'https://Stackoverflow.com/users/4257', 'pm_score': 8, 'selected': False, 'text': '<p>Yes, the order depends on the specific Map implementation.</p>\n\n<p><a href="https://stackoverflow.com/questions/46898/how-to-efficiently-iterate-over-each-entry-in-a-map/46908#46908">@ScArcher2 has the more elegant Java 1.5 syntax</a>. In 1.4, I would do something like this:</p>\n\n<pre><code>Iterator entries = myMap.entrySet().iterator();\nwhile (entries.hasNext()) {\n  Entry thisEntry = (Entry) entries.next();\n  Object key = thisEntry.getKey();\n  Object value = thisEntry.getValue();\n  // ...\n}\n</code></pre>\n'}, {'answer_id': 46908, 'author': 'ScArcher2', 'author_id': 1310, 'author_profile': 'https://Stackoverflow.com/users/1310', 'pm_score': 13, 'selected': True, 'text': '<pre class="lang-java prettyprint-override"><code>Map&lt;String, String&gt; map = ...\nfor (Map.Entry&lt;String, String&gt; entry : map.entrySet()) {\n    System.out.println(entry.getKey() + &quot;/&quot; + entry.getValue());\n}\n</code></pre>\n<p>On Java 10+:</p>\n<pre class="lang-java prettyprint-override"><code>for (var entry : map.entrySet()) {\n    System.out.println(entry.getKey() + &quot;/&quot; + entry.getValue());\n}\n</code></pre>\n'}, {'answer_id': 46912, 'author': 'Leigh Caldwell', 'author_id': 3267, 'author_profile': 'https://Stackoverflow.com/users/3267', 'pm_score': 5, 'selected': False, 'text': "<p>In theory, the most efficient way will depend on which implementation of Map. The official way to do this is to call <code>map.entrySet()</code>, which returns a set of <code>Map.Entry</code>, each of which contains a key and a value (<code>entry.getKey()</code> and <code>entry.getValue()</code>).</p>\n\n<p>In an idiosyncratic implementation, it might make some difference whether you use <code>map.keySet()</code>, <code>map.entrySet()</code> or something else. But I can't think of a reason why anyone would write it like that. Most likely it makes no difference to performance what you do.</p>\n\n<p>And yes, the order will depend on the implementation - as well as (possibly) the order of insertion and other hard-to-control factors.</p>\n\n<p>[edit] I wrote <code>valueSet()</code> originally but of course <code>entrySet()</code> is actually the answer.</p>\n"}, {'answer_id': 46926, 'author': 'Tom Hawtin - tackline', 'author_id': 4725, 'author_profile': 'https://Stackoverflow.com/users/4725', 'pm_score': 7, 'selected': False, 'text': "<p>Typical code for iterating over a map is:</p>\n<pre><code>Map&lt;String,Thing&gt; map = ...;\nfor (Map.Entry&lt;String,Thing&gt; entry : map.entrySet()) {\n    String key = entry.getKey();\n    Thing thing = entry.getValue();\n    ...\n}\n</code></pre>\n<p><code>HashMap</code> is the canonical map implementation and doesn't make guarantees (or though it should not change the order if no mutating operations are performed on it). <code>SortedMap</code> will return entries based on the natural ordering of the keys, or a <code>Comparator</code>, if provided. <code>LinkedHashMap</code> will either return entries in insertion-order or access-order depending upon how it has been constructed. <code>EnumMap</code> returns entries in the natural order of keys.</p>\n<p><strong>(Update: I think this is no longer true.</strong>) Note, <code>IdentityHashMap</code> <code>entrySet</code> iterator currently has a peculiar implementation which returns the same <code>Map.Entry</code> instance for every item in the <code>entrySet</code>! However, every time a new iterator advances the <code>Map.Entry</code> is updated.</p>\n"}, {'answer_id': 46989, 'author': 'serg10', 'author_id': 1853, 'author_profile': 'https://Stackoverflow.com/users/1853', 'pm_score': 7, 'selected': False, 'text': '<p>This is a two part question:</p>\n\n<p><em>How to iterate over the entries of a Map</em> - @ScArcher2 has <a href="https://stackoverflow.com/a/46908/1851302">answered</a> that perfectly.</p>\n\n<p><em>What is the order of iteration</em> - if you are just using <code>Map</code>, then strictly speaking, there are <strong>no ordering guarantees</strong>.  So you shouldn\'t really rely on the ordering given by any implementation.  However, the <a href="http://docs.oracle.com/javase/8/docs/api/java/util/SortedMap.html" rel="noreferrer"><code>SortedMap</code></a> interface extends <code>Map</code> and provides exactly what you are looking for - implementations will aways give a consistent sort order.</p>\n\n<p><strong><a href="http://docs.oracle.com/javase/8/docs/api/java/util/NavigableMap.html" rel="noreferrer"><code>NavigableMap</code></a> is another useful extension</strong> - this is a <code>SortedMap</code> with additional methods for finding entries by their ordered position in the key set.  So potentially this can remove the need for iterating in the first place - you might be able to find the specific <code>entry</code> you are after using the <code>higherEntry</code>, <code>lowerEntry</code>, <code>ceilingEntry</code>, or <code>floorEntry</code> methods.  The <code>descendingMap</code> method even gives you an explicit method of <strong>reversing the traversal order</strong>.</p>\n'}, {'answer_id': 47004, 'author': 'ckpwong', 'author_id': 2551, 'author_profile': 'https://Stackoverflow.com/users/2551', 'pm_score': 6, 'selected': False, 'text': "<p>FYI, you can also use <code>map.keySet()</code> and <code>map.values()</code> if you're only interested in keys/values of the map and not the other.</p>\n"}, {'answer_id': 48720, 'author': 'Chris Dail', 'author_id': 5077, 'author_profile': 'https://Stackoverflow.com/users/5077', 'pm_score': 6, 'selected': False, 'text': '<p>The correct way to do this is to use the accepted answer as it is the most efficient. I find the following code looks a bit cleaner.</p>\n\n<pre><code>for (String key: map.keySet()) {\n   System.out.println(key + "/" + map.get(key));\n}\n</code></pre>\n'}, {'answer_id': 1295383, 'author': 'serg', 'author_id': 20128, 'author_profile': 'https://Stackoverflow.com/users/20128', 'pm_score': 7, 'selected': False, 'text': '<p>Example of using iterator and generics:</p>\n\n<pre><code>Iterator&lt;Map.Entry&lt;String, String&gt;&gt; entries = myMap.entrySet().iterator();\nwhile (entries.hasNext()) {\n  Map.Entry&lt;String, String&gt; entry = entries.next();\n  String key = entry.getKey();\n  String value = entry.getValue();\n  // ...\n}\n</code></pre>\n'}, {'answer_id': 2190043, 'author': 'abods', 'author_id': 265011, 'author_profile': 'https://Stackoverflow.com/users/265011', 'pm_score': 5, 'selected': False, 'text': '<p>Try this with Java 1.4:</p>\n\n<pre><code>for( Iterator entries = myMap.entrySet().iterator(); entries.hasNext();){\n\n  Entry entry = (Entry) entries.next();\n\n  System.out.println(entry.getKey() + "/" + entry.getValue());\n\n  //...\n}\n</code></pre>\n'}, {'answer_id': 10632923, 'author': 'Fathah Rehman P', 'author_id': 991065, 'author_profile': 'https://Stackoverflow.com/users/991065', 'pm_score': 4, 'selected': False, 'text': '<pre><code>public class abcd{\n    public static void main(String[] args)\n    {\n       Map&lt;Integer, String&gt; testMap = new HashMap&lt;Integer, String&gt;();\n        testMap.put(10, "a");\n        testMap.put(20, "b");\n        testMap.put(30, "c");\n        testMap.put(40, "d");\n        for (Integer key:testMap.keySet()) {\n            String value=testMap.get(key);\n            System.out.println(value);\n        }\n    }\n}\n</code></pre>\n\n<p>OR</p>\n\n<pre><code>public class abcd {\n    public static void main(String[] args)\n    {\n       Map&lt;Integer, String&gt; testMap = new HashMap&lt;Integer, String&gt;();\n        testMap.put(10, "a");\n        testMap.put(20, "b");\n        testMap.put(30, "c");\n        testMap.put(40, "d");\n        for (Entry&lt;Integer, String&gt; entry : testMap.entrySet()) {\n            Integer key=entry.getKey();\n            String value=entry.getValue();\n        }\n    }\n}\n</code></pre>\n'}, {'answer_id': 13943066, 'author': 'Donald Raab', 'author_id': 1570415, 'author_profile': 'https://Stackoverflow.com/users/1570415', 'pm_score': 5, 'selected': False, 'text': '<p>With <a href="https://github.com/eclipse/eclipse-collections" rel="noreferrer">Eclipse Collections</a>, you would use the <code>forEachKeyValue</code> method on the <a href="https://github.com/eclipse/eclipse-collections/blob/master/eclipse-collections-api/src/main/java/org/eclipse/collections/api/map/MapIterable.java" rel="noreferrer"><code>MapIterable</code></a> interface, which is inherited by the <code>MutableMap</code> and <code>ImmutableMap</code> interfaces and their implementations.</p>\n\n<pre><code>MutableBag&lt;String&gt; result = Bags.mutable.empty();\nMutableMap&lt;Integer, String&gt; map = Maps.mutable.of(1, "One", 2, "Two", 3, "Three");\nmap.forEachKeyValue((key, value) -&gt; result.add(key + value));\nAssert.assertEquals(Bags.mutable.of("1One", "2Two", "3Three"), result);\n</code></pre>\n\n<p>Using an anonymous inner class, you can write the code as follows:</p>\n\n<pre><code>final MutableBag&lt;String&gt; result = Bags.mutable.empty();\nMutableMap&lt;Integer, String&gt; map = Maps.mutable.of(1, "One", 2, "Two", 3, "Three");\nmap.forEachKeyValue(new Procedure2&lt;Integer, String&gt;()\n{\n    public void value(Integer key, String value)\n    {\n        result.add(key + value);\n    }\n});\nAssert.assertEquals(Bags.mutable.of("1One", "2Two", "3Three"), result);\n</code></pre>\n\n<p><strong>Note:</strong> I am a committer for Eclipse Collections.</p>\n'}, {'answer_id': 15556457, 'author': 'Suresh Atta', 'author_id': 1927832, 'author_profile': 'https://Stackoverflow.com/users/1927832', 'pm_score': 3, 'selected': False, 'text': "<p>Yes, as many people agreed this is the best way to iterate over a <code>Map</code>.</p>\n\n<p>But there are chances to throw <code>nullpointerexception</code> if the map is <code>null</code>. Don't forget to put <code>null</code> .check in.</p>\n\n<pre><code>                                                 |\n                                                 |\n                                         - - - -\n                                       |\n                                       |\nfor (Map.Entry&lt;String, Object&gt; entry : map.entrySet()) {\n    String key = entry.getKey();\n    Object value = entry.getValue();\n}\n</code></pre>\n"}, {'answer_id': 17404976, 'author': 'Learner', 'author_id': 1918772, 'author_profile': 'https://Stackoverflow.com/users/1918772', 'pm_score': 4, 'selected': False, 'text': '<p>You can do it using generics:</p>\n\n<pre><code>Map&lt;Integer, Integer&gt; map = new HashMap&lt;Integer, Integer&gt;();\nIterator&lt;Map.Entry&lt;Integer, Integer&gt;&gt; entries = map.entrySet().iterator();\nwhile (entries.hasNext()) {\n    Map.Entry&lt;Integer, Integer&gt; entry = entries.next();\n    System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());\n}\n</code></pre>\n'}, {'answer_id': 19491759, 'author': 'The Coordinator', 'author_id': 1584255, 'author_profile': 'https://Stackoverflow.com/users/1584255', 'pm_score': 8, 'selected': False, 'text': '<p>In Java 8 you can do it clean and fast using the new lambdas features:</p>\n\n<pre><code> Map&lt;String,String&gt; map = new HashMap&lt;&gt;();\n map.put("SomeKey", "SomeValue");\n map.forEach( (k,v) -&gt; [do something with key and value] );\n\n // such as\n map.forEach( (k,v) -&gt; System.out.println("Key: " + k + ": Value: " + v));\n</code></pre>\n\n<p>The type of <code>k</code> and <code>v</code> will be inferred by the compiler and there is no need to use <code>Map.Entry</code> anymore.</p>\n\n<p>Easy-peasy!</p>\n'}, {'answer_id': 20286334, 'author': 'dmunozfer', 'author_id': 1276364, 'author_profile': 'https://Stackoverflow.com/users/1276364', 'pm_score': 5, 'selected': False, 'text': '<p>If you have a generic untyped Map you can use:</p>\n\n<pre><code>Map map = new HashMap();\nfor (Map.Entry entry : ((Set&lt;Map.Entry&gt;) map.entrySet())) {\n    System.out.println(entry.getKey() + "/" + entry.getValue());\n}\n</code></pre>\n'}, {'answer_id': 20903678, 'author': 'J.B.Vala', 'author_id': 3141443, 'author_profile': 'https://Stackoverflow.com/users/3141443', 'pm_score': 3, 'selected': False, 'text': '<p>There are several ways to iterate a map. Please refer to the following code.</p>\n<p>When you iterate a map using iterator Interface you must go with <code>Entry&lt;K,V&gt;</code> or <code>entrySet()</code>.</p>\n<p>It looks like this:</p>\n<pre class="lang-java prettyprint-override"><code>    import java.util.*;\n    import java.util.HashMap;\n    import java.util.Iterator;\n    import java.util.Map;\n\n    public class IteratMapDemo{\n\n        public static void main(String arg[]){\n            Map&lt;String, String&gt; mapOne = new HashMap&lt;String, String&gt;();\n            mapOne.put(&quot;1&quot;, &quot;January&quot;);\n            mapOne.put(&quot;2&quot;, &quot;February&quot;);\n            mapOne.put(&quot;3&quot;, &quot;March&quot;);\n            mapOne.put(&quot;4&quot;, &quot;April&quot;);\n            mapOne.put(&quot;5&quot;, &quot;May&quot;);\n            mapOne.put(&quot;6&quot;, &quot;June&quot;);\n            mapOne.put(&quot;7&quot;, &quot;July&quot;);\n            mapOne.put(&quot;8&quot;, &quot;August&quot;);\n            mapOne.put(&quot;9&quot;, &quot;September&quot;);\n            mapOne.put(&quot;10&quot;, &quot;Octomber&quot;);\n            mapOne.put(&quot;11&quot;, &quot;November&quot;);\n            mapOne.put(&quot;12&quot;, &quot;December&quot;);\n\n            Iterator it = mapOne.entrySet().iterator();\n            while(it.hasNext())\n            {\n                Map.Entry me = (Map.Entry) it.next();\n                //System.out.println(&quot;Get Key through While loop = &quot; + me.getKey());\n            }\n            for(Map.Entry&lt;String, String&gt; entry:mapOne.entrySet()){\n                //System.out.println(entry.getKey() + &quot;=&quot; + entry.getValue());\n            }\n\n            for (Object key : mapOne.keySet()) {\n                System.out.println(&quot;Key: &quot; + key.toString() + &quot; Value: &quot; +\n                                   mapOne.get(key));\n            }\n        }\n    }\n</code></pre>\n'}, {'answer_id': 21431305, 'author': 'Rupesh Yadav', 'author_id': 918472, 'author_profile': 'https://Stackoverflow.com/users/918472', 'pm_score': 5, 'selected': False, 'text': '<p>In Map one can Iteration over <code>keys</code> and/or <code>values</code> and/or <code>both (e.g., entrySet)</code>  depends on one\'s interested in_ Like:</p>\n<ol>\n<li><p>Iterate through the <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/Map.html#keySet%28%29" rel="nofollow noreferrer"><code>keys -&gt; keySet()</code></a> of the map:</p>\n<pre><code> Map&lt;String, Object&gt; map = ...;\n\n for (String key : map.keySet()) {\n     //your Business logic...\n }\n</code></pre>\n</li>\n<li><p>Iterate through the <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/Map.html#values%28%29" rel="nofollow noreferrer"><code>values -&gt; values()</code></a> of the map:</p>\n<pre><code> for (Object value : map.values()) {\n     //your Business logic...\n }\n</code></pre>\n</li>\n<li><p>Iterate through the <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/Map.html#entrySet%28%29" rel="nofollow noreferrer"><code>both -&gt; entrySet()</code></a> of the map:</p>\n<pre><code> for (Map.Entry&lt;String, Object&gt; entry : map.entrySet()) {\n     String key = entry.getKey();\n     Object value = entry.getValue();\n     //your Business logic...\n }\n</code></pre>\n</li>\n</ol>\n<p>Moreover, there are 3 different ways to iterate through a HashMap. They are as below:</p>\n<pre><code>//1.\nfor (Map.Entry entry : hm.entrySet()) {\n    System.out.print(&quot;key,val: &quot;);\n    System.out.println(entry.getKey() + &quot;,&quot; + entry.getValue());\n}\n\n//2.\nIterator iter = hm.keySet().iterator();\nwhile(iter.hasNext()) {\n    Integer key = (Integer)iter.next();\n    String val = (String)hm.get(key);\n    System.out.println(&quot;key,val: &quot; + key + &quot;,&quot; + val);\n}\n\n//3.\nIterator it = hm.entrySet().iterator();\nwhile (it.hasNext()) {\n    Map.Entry entry = (Map.Entry) it.next();\n    Integer key = (Integer)entry.getKey();\n    String val = (String)entry.getValue();\n    System.out.println(&quot;key,val: &quot; + key + &quot;,&quot; + val);\n}\n</code></pre>\n'}, {'answer_id': 21570332, 'author': 'Darshan Patel', 'author_id': 3131537, 'author_profile': 'https://Stackoverflow.com/users/3131537', 'pm_score': 6, 'selected': False, 'text': '<p>There are several ways to iterate over map.</p>\n\n<p>Here is comparison of their performances for a common data set stored in map by storing a million key value pairs in map and will iterate over map.</p>\n\n<p><strong>1) Using <code>entrySet()</code> in for each loop</strong></p>\n\n<pre><code>for (Map.Entry&lt;String,Integer&gt; entry : testMap.entrySet()) {\n    entry.getKey();\n    entry.getValue();\n}\n</code></pre>\n\n<p><em>50 milliseconds</em></p>\n\n<p><strong>2) Using <code>keySet()</code> in for each loop</strong></p>\n\n<pre><code>for (String key : testMap.keySet()) {\n    testMap.get(key);\n}\n</code></pre>\n\n<p><em>76 milliseconds</em></p>\n\n<p><strong>3) Using <code>entrySet()</code> and iterator</strong></p>\n\n<pre><code>Iterator&lt;Map.Entry&lt;String,Integer&gt;&gt; itr1 = testMap.entrySet().iterator();\nwhile(itr1.hasNext()) {\n    Map.Entry&lt;String,Integer&gt; entry = itr1.next();\n    entry.getKey();\n    entry.getValue();\n}\n</code></pre>\n\n<p><em>50 milliseconds</em></p>\n\n<p><strong>4) Using <code>keySet()</code> and iterator</strong></p>\n\n<pre><code>Iterator itr2 = testMap.keySet().iterator();\nwhile(itr2.hasNext()) {\n    String key = itr2.next();\n    testMap.get(key);\n}\n</code></pre>\n\n<p><em>75 milliseconds</em></p>\n\n<p>I have referred <a href="http://howtodoinjava.com/2013/04/01/performance-comparison-of-different-ways-to-iterate-over-hashmap/" rel="noreferrer"><code>this link</code></a>.</p>\n'}, {'answer_id': 22513787, 'author': 'Fadid', 'author_id': 3254469, 'author_profile': 'https://Stackoverflow.com/users/3254469', 'pm_score': 4, 'selected': False, 'text': '<pre><code>    Iterator iterator = map.entrySet().iterator();\n    while (iterator.hasNext()) {\n        Map.Entry element = (Map.Entry)it.next();\n        LOGGER.debug("Key: " + element.getKey());\n        LOGGER.debug("value: " + element.getValue());    \n    }\n</code></pre>\n'}, {'answer_id': 25116661, 'author': 'Georgios Syngouroglou', 'author_id': 1123501, 'author_profile': 'https://Stackoverflow.com/users/1123501', 'pm_score': 5, 'selected': False, 'text': '<p><strong>Java 8:</strong></p>\n\n<p>You can use lambda expressions:</p>\n\n<pre><code>myMap.entrySet().stream().forEach((entry) -&gt; {\n    Object currentKey = entry.getKey();\n    Object currentValue = entry.getValue();\n});\n</code></pre>\n\n<p>For more information, follow <a href="http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html" rel="noreferrer">this</a>.</p>\n'}, {'answer_id': 25436802, 'author': 'fechidal89', 'author_id': 1941878, 'author_profile': 'https://Stackoverflow.com/users/1941878', 'pm_score': 2, 'selected': False, 'text': '<p>I copied the data of a map to another with this code:</p>\n\n<pre><code>HashMap product =(HashMap)shopping_truck.get(i);\nHashMap tmp = new HashMap();\nfor (Iterator it = product.entrySet().iterator(); it.hasNext();) {\n    Map.Entry thisEntry = (Map.Entry) it.next();\n    tmp.put(thisEntry.getKey(), thisEntry.getValue());\n}\n</code></pre>\n'}, {'answer_id': 27871427, 'author': 'JohnK', 'author_id': 1431728, 'author_profile': 'https://Stackoverflow.com/users/1431728', 'pm_score': 2, 'selected': False, 'text': '<p>It doesn\'t quite answer the OP\'s question, but might be useful to others who find this page:</p>\n\n<p>If you only need the values and not the keys, you can do this:</p>\n\n<pre><code>Map&lt;Ktype, Vtype&gt; myMap = [...];\nfor (Vtype v: myMap.values()) {\n  System.out.println("value: " + v);\n}\n</code></pre>\n\n<p><code>Ktype</code>, <code>Vtype</code> are pseudocode.</p>\n'}, {'answer_id': 30215019, 'author': 'Mr. Polywhirl', 'author_id': 1762224, 'author_profile': 'https://Stackoverflow.com/users/1762224', 'pm_score': 3, 'selected': False, 'text': '<p>Here is a generic type-safe method which can be called to dump any given <code>Map</code>.</p>\n\n<pre><code>import java.util.Iterator;\nimport java.util.Map;\n\npublic class MapUtils {\n    static interface ItemCallback&lt;K, V&gt; {\n        void handler(K key, V value, Map&lt;K, V&gt; map);\n    }\n\n    public static &lt;K, V&gt; void forEach(Map&lt;K, V&gt; map, ItemCallback&lt;K, V&gt; callback) {\n        Iterator&lt;Map.Entry&lt;K, V&gt;&gt; it = map.entrySet().iterator();\n\n        while (it.hasNext()) {\n            Map.Entry&lt;K, V&gt; entry = it.next();\n\n            callback.handler(entry.getKey(), entry.getValue(), map);\n        }\n    }\n\n    public static &lt;K, V&gt; void printMap(Map&lt;K, V&gt; map) {\n        forEach(map, new ItemCallback&lt;K, V&gt;() {\n            @Override\n            public void handler(K key, V value, Map&lt;K, V&gt; map) {\n                System.out.println(key + " = " + value);\n            }\n        });\n    }\n}\n</code></pre>\n\n<h2>Example</h2>\n\n<p>Here is an example of its use. Notice that the type of the <code>Map</code> is inferred by the method.</p>\n\n<pre><code>import java.util.*;\n\npublic class MapPrinter {\n    public static void main(String[] args) {\n        List&lt;Map&lt;?, ?&gt;&gt; maps = new ArrayList&lt;Map&lt;?, ?&gt;&gt;() {\n            private static final long serialVersionUID = 1L;\n            {\n                add(new LinkedHashMap&lt;String, Integer&gt;() {\n                    private static final long serialVersionUID = 1L;\n                    {\n                        put("One", 0);\n                        put("Two", 1);\n                        put("Three", 3);\n                    }\n                });\n\n                add(new LinkedHashMap&lt;String, Object&gt;() {\n                    private static final long serialVersionUID = 1L;\n                    {\n                        put("Object", new Object());\n                        put("Integer", new Integer(0));\n                        put("Double", new Double(0.0));\n                    }\n                });\n            }\n        };\n\n        for (Map&lt;?, ?&gt; map : maps) {\n            MapUtils.printMap(map);\n            System.out.println();\n        }\n    }\n}\n</code></pre>\n\n<h2>Output</h2>\n\n<pre><code>One = 0\nTwo = 1\nThree = 3\n\nObject = java.lang.Object@15db9742\nInteger = 0\nDouble = 0.0\n</code></pre>\n'}, {'answer_id': 30550239, 'author': 'Joshua Michael Calafell', 'author_id': 2197975, 'author_profile': 'https://Stackoverflow.com/users/2197975', 'pm_score': 2, 'selected': False, 'text': '<p>This is the easiest way of doing it I believe...</p>\n\n<pre><code>/* For example, this could be a map object */\nMap&lt;String, Integer&gt; MAP = new Map&lt;&gt;();\n\n// Do something like put keys/value pairs into the map, etc...\nMAP.put("Denver", 35);\nMAP.put("Patriots", 14);\n\n/* Then, simply use a for each loop like this to iterate */\nfor (Object o : MAP.entrySet()) {\n    Map.Entry pair = (Map.Entry) o;\n    // Do whatever with the pair here (i.e. pair.getKey(), or pair.getValue();\n}\n</code></pre>\n'}, {'answer_id': 32288690, 'author': 'tomaj', 'author_id': 1758634, 'author_profile': 'https://Stackoverflow.com/users/1758634', 'pm_score': 3, 'selected': False, 'text': '<p>If your reason for iterating trough the <code>Map</code>, is to do an operation on the value and write to a resulting <code>Map</code>. I recommend using the <code>transform</code>-methods in the <a href="https://github.com/google/guava" rel="noreferrer">Google Guava</a> <code>Maps</code> class.</p>\n\n<pre><code>import com.google.common.collect.Maps;\n</code></pre>\n\n<p>After you have added the <code>Maps</code> to your imports, you can use <code>Maps.transformValues</code> and <code>Maps.transformEntries</code> on your maps, like this:</p>\n\n<pre><code>public void transformMap(){\n    Map&lt;String, Integer&gt; map = new HashMap&lt;&gt;();\n    map.put("a", 2);\n    map.put("b", 4);\n\n    Map&lt;String, Integer&gt; result = Maps.transformValues(map, num -&gt; num * 2);\n    result.forEach((key, val) -&gt; print(key, Integer.toString(val)));\n    // key=a,value=4\n    // key=b,value=8\n\n    Map&lt;String, String&gt; result2 = Maps.transformEntries(map, (key, value) -&gt; value + "[" + key + "]");\n    result2.forEach(this::print);\n    // key=a,value=2[a]\n    // key=b,value=4[b]\n}\n\nprivate void print(String key, String val){\n    System.out.println("key=" + key + ",value=" + val);\n}\n</code></pre>\n'}, {'answer_id': 32343110, 'author': 'akhil_mittal', 'author_id': 1216775, 'author_profile': 'https://Stackoverflow.com/users/1216775', 'pm_score': 5, 'selected': False, 'text': '<h2>Java 8</h2>\n\n<p>We have got <code>forEach</code> method that accepts a <a href="https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html" rel="noreferrer">lambda expression</a>. We have also got <a href="https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html" rel="noreferrer">stream</a> APIs. Consider a map:</p>\n\n<pre><code>Map&lt;String,String&gt; sample = new HashMap&lt;&gt;();\nsample.put("A","Apple");\nsample.put("B", "Ball");\n</code></pre>\n\n<p><strong>Iterate over keys:</strong></p>\n\n<pre><code>sample.keySet().forEach((k) -&gt; System.out.println(k));\n</code></pre>\n\n<p><strong>Iterate over values:</strong></p>\n\n<pre><code>sample.values().forEach((v) -&gt; System.out.println(v));\n</code></pre>\n\n<p><strong>Iterate over entries (Using forEach and Streams):</strong></p>\n\n<pre><code>sample.forEach((k,v) -&gt; System.out.println(k + ":" + v)); \nsample.entrySet().stream().forEach((entry) -&gt; {\n            Object currentKey = entry.getKey();\n            Object currentValue = entry.getValue();\n            System.out.println(currentKey + ":" + currentValue);\n        });\n</code></pre>\n\n<p>The advantage with streams is they can be parallelized easily in case we want to. We simply need to use <code>parallelStream()</code> in place of <code>stream()</code> above.</p>\n\n<p><strong><code>forEachOrdered</code> vs <code>forEach</code> with streams ?</strong>\nThe <code>forEach</code> does not follow encounter order (if defined) and is inherently non-deterministic in nature where as the <code>forEachOrdered</code> does. So <code>forEach</code> does not guarantee that the order would be kept. Also check <a href="https://stackoverflow.com/questions/32797579/foreach-vs-foreachordered-in-java-8-stream">this</a> for more.</p>\n'}, {'answer_id': 32973406, 'author': 'Nitin Mahesh', 'author_id': 1503859, 'author_profile': 'https://Stackoverflow.com/users/1503859', 'pm_score': 5, 'selected': False, 'text': '<blockquote>\n  <p><strong>Lambda</strong> Expression Java 8</p>\n</blockquote>\n\n<p>In Java 1.8 (Java 8) this has become lot easier by using <strong>forEach</strong> method from Aggregate operations(<strong>Stream operations</strong>) that looks similar to iterators from <strong>Iterable</strong> Interface. </p>\n\n<p>Just copy paste below statement to your code and rename the <strong>HashMap</strong> variable from <strong>hm</strong> to your HashMap variable to print out key-value pair.</p>\n\n<pre><code>HashMap&lt;Integer,Integer&gt; hm = new HashMap&lt;Integer, Integer&gt;();\n/*\n *     Logic to put the Key,Value pair in your HashMap hm\n */\n\n// Print the key value pair in one line.\n\nhm.forEach((k, v) -&gt; System.out.println("key: " + k + " value:" + v));\n\n// Just copy and paste above line to your code.\n</code></pre>\n\n<p>Below is the sample code that I tried using <strong>Lambda Expression</strong>. This stuff is so cool. Must try.</p>\n\n<pre><code>HashMap&lt;Integer, Integer&gt; hm = new HashMap&lt;Integer, Integer&gt;();\n    Random rand = new Random(47);\n    int i = 0;\n    while(i &lt; 5) {\n        i++;\n        int key = rand.nextInt(20);\n        int value = rand.nextInt(50);\n        System.out.println("Inserting key: " + key + " Value: " + value);\n        Integer imap = hm.put(key, value);\n        if( imap == null) {\n            System.out.println("Inserted");\n        } else {\n            System.out.println("Replaced with " + imap);\n        }               \n    }\n\n    hm.forEach((k, v) -&gt; System.out.println("key: " + k + " value:" + v));\n\nOutput:\n\nInserting key: 18 Value: 5\nInserted\nInserting key: 13 Value: 11\nInserted\nInserting key: 1 Value: 29\nInserted\nInserting key: 8 Value: 0\nInserted\nInserting key: 2 Value: 7\nInserted\nkey: 1 value:29\nkey: 18 value:5\nkey: 2 value:7\nkey: 8 value:0\nkey: 13 value:11\n</code></pre>\n\n<p>Also one can use <strong>Spliterator</strong> for the same.</p>\n\n<pre><code>Spliterator sit = hm.entrySet().spliterator();\n</code></pre>\n\n<p><strong>UPDATE</strong></p>\n\n<hr>\n\n<p>Including documentation links to Oracle Docs.\nFor more on <strong>Lambda</strong> go to this <a href="https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html" rel="noreferrer">link</a> and must read <a href="https://docs.oracle.com/javase/tutorial/collections/streams/" rel="noreferrer">Aggregate Operations</a> and for Spliterator go to this <a href="https://docs.oracle.com/javase/8/docs/api/java/util/Spliterator.html" rel="noreferrer">link</a>.</p>\n'}, {'answer_id': 33375492, 'author': 'Syd Lambert', 'author_id': 5135746, 'author_profile': 'https://Stackoverflow.com/users/5135746', 'pm_score': 2, 'selected': False, 'text': '<p>If you want to iterate through the map in the order that the elements were added, use <code>LinkedHashMap</code> as opposed to just <code>Map</code>.</p>\n\n<p>This approach has worked for me in the past:</p>\n\n<pre><code>LinkedHashMap&lt;String,Integer&gt; test=new LinkedHashMap();\n\ntest.put("foo",69);\ntest.put("bar",1337);\n\nfor(int i=0;i&lt;test.size();i++){\n    System.out.println(test.get(test.keySet().toArray()[i]));\n}\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>69\n1337\n</code></pre>\n'}, {'answer_id': 35558955, 'author': 'Slava Vedenin', 'author_id': 4318868, 'author_profile': 'https://Stackoverflow.com/users/4318868', 'pm_score': 11, 'selected': False, 'text': '<p>To summarize the other answers and combine them with what I know, I found 10 main ways to do this (see below). Also, I wrote some performance tests (see results below). For example, if we want to find the sum of all of the keys and values of a map, we can write:</p>\n\n<ol>\n<li><p>Using <strong>iterator</strong> and <strong>Map.Entry</strong></p>\n\n<pre><code>long i = 0;\nIterator&lt;Map.Entry&lt;Integer, Integer&gt;&gt; it = map.entrySet().iterator();\nwhile (it.hasNext()) {\n    Map.Entry&lt;Integer, Integer&gt; pair = it.next();\n    i += pair.getKey() + pair.getValue();\n}\n</code></pre></li>\n<li><p>Using <strong>foreach</strong> and <strong>Map.Entry</strong></p>\n\n<pre><code>long i = 0;\nfor (Map.Entry&lt;Integer, Integer&gt; pair : map.entrySet()) {\n    i += pair.getKey() + pair.getValue();\n}\n</code></pre></li>\n<li><p>Using <strong>forEach</strong> from Java 8</p>\n\n<pre><code>final long[] i = {0};\nmap.forEach((k, v) -&gt; i[0] += k + v);\n</code></pre></li>\n<li><p>Using <strong>keySet</strong> and <strong>foreach</strong></p>\n\n<pre><code>long i = 0;\nfor (Integer key : map.keySet()) {\n    i += key + map.get(key);\n}\n</code></pre></li>\n<li><p>Using <strong>keySet</strong> and <strong>iterator</strong></p>\n\n<pre><code>long i = 0;\nIterator&lt;Integer&gt; itr2 = map.keySet().iterator();\nwhile (itr2.hasNext()) {\n    Integer key = itr2.next();\n    i += key + map.get(key);\n}\n</code></pre></li>\n<li><p>Using <strong>for</strong> and <strong>Map.Entry</strong></p>\n\n<pre><code>long i = 0;\nfor (Iterator&lt;Map.Entry&lt;Integer, Integer&gt;&gt; entries = map.entrySet().iterator(); entries.hasNext(); ) {\n    Map.Entry&lt;Integer, Integer&gt; entry = entries.next();\n    i += entry.getKey() + entry.getValue();\n}\n</code></pre></li>\n<li><p>Using the Java 8 <strong>Stream API</strong></p>\n\n<pre><code>final long[] i = {0};\nmap.entrySet().stream().forEach(e -&gt; i[0] += e.getKey() + e.getValue());\n</code></pre></li>\n<li><p>Using the Java 8 <strong>Stream API parallel</strong></p>\n\n<pre><code>final long[] i = {0};\nmap.entrySet().stream().parallel().forEach(e -&gt; i[0] += e.getKey() + e.getValue());\n</code></pre></li>\n<li><p>Using <strong>IterableMap</strong> of <code>Apache Collections</code></p>\n\n<pre><code>long i = 0;\nMapIterator&lt;Integer, Integer&gt; it = iterableMap.mapIterator();\nwhile (it.hasNext()) {\n    i += it.next() + it.getValue();\n}\n</code></pre></li>\n<li><p>Using <strong>MutableMap</strong> of Eclipse (CS) collections</p>\n\n<pre><code>final long[] i = {0};\nmutableMap.forEachKeyValue((key, value) -&gt; {\n    i[0] += key + value;\n});\n</code></pre></li>\n</ol>\n\n<p><strong>Perfomance tests</strong> (mode = AverageTime, system = Windows&nbsp;8.1 64-bit, Intel i7-4790 3.60 GHz, 16&nbsp;GB)</p>\n\n<ol>\n<li><p>For a small map (100 elements), score 0.308 is the best</p>\n\n<pre><code>Benchmark                          Mode  Cnt  Score    Error  Units\ntest3_UsingForEachAndJava8         avgt  10   0.308 ±  0.021  µs/op\ntest10_UsingEclipseMap             avgt  10   0.309 ±  0.009  µs/op\ntest1_UsingWhileAndMapEntry        avgt  10   0.380 ±  0.014  µs/op\ntest6_UsingForAndIterator          avgt  10   0.387 ±  0.016  µs/op\ntest2_UsingForEachAndMapEntry      avgt  10   0.391 ±  0.023  µs/op\ntest7_UsingJava8StreamApi          avgt  10   0.510 ±  0.014  µs/op\ntest9_UsingApacheIterableMap       avgt  10   0.524 ±  0.008  µs/op\ntest4_UsingKeySetAndForEach        avgt  10   0.816 ±  0.026  µs/op\ntest5_UsingKeySetAndIterator       avgt  10   0.863 ±  0.025  µs/op\ntest8_UsingJava8StreamApiParallel  avgt  10   5.552 ±  0.185  µs/op\n</code></pre></li>\n<li><p>For a map with 10000 elements,  score 37.606 is the best</p>\n\n<pre><code>Benchmark                           Mode   Cnt  Score      Error   Units\ntest10_UsingEclipseMap              avgt   10    37.606 ±   0.790  µs/op\ntest3_UsingForEachAndJava8          avgt   10    50.368 ±   0.887  µs/op\ntest6_UsingForAndIterator           avgt   10    50.332 ±   0.507  µs/op\ntest2_UsingForEachAndMapEntry       avgt   10    51.406 ±   1.032  µs/op\ntest1_UsingWhileAndMapEntry         avgt   10    52.538 ±   2.431  µs/op\ntest7_UsingJava8StreamApi           avgt   10    54.464 ±   0.712  µs/op\ntest4_UsingKeySetAndForEach         avgt   10    79.016 ±  25.345  µs/op\ntest5_UsingKeySetAndIterator        avgt   10    91.105 ±  10.220  µs/op\ntest8_UsingJava8StreamApiParallel   avgt   10   112.511 ±   0.365  µs/op\ntest9_UsingApacheIterableMap        avgt   10   125.714 ±   1.935  µs/op\n</code></pre></li>\n<li><p>For a map with 100000 elements,  score 1184.767 is the best</p>\n\n<pre><code>Benchmark                          Mode   Cnt  Score        Error    Units\ntest1_UsingWhileAndMapEntry        avgt   10   1184.767 ±   332.968  µs/op\ntest10_UsingEclipseMap             avgt   10   1191.735 ±   304.273  µs/op\ntest2_UsingForEachAndMapEntry      avgt   10   1205.815 ±   366.043  µs/op\ntest6_UsingForAndIterator          avgt   10   1206.873 ±   367.272  µs/op\ntest8_UsingJava8StreamApiParallel  avgt   10   1485.895 ±   233.143  µs/op\ntest5_UsingKeySetAndIterator       avgt   10   1540.281 ±   357.497  µs/op\ntest4_UsingKeySetAndForEach        avgt   10   1593.342 ±   294.417  µs/op\ntest3_UsingForEachAndJava8         avgt   10   1666.296 ±   126.443  µs/op\ntest7_UsingJava8StreamApi          avgt   10   1706.676 ±   436.867  µs/op\ntest9_UsingApacheIterableMap       avgt   10   3289.866 ±  1445.564  µs/op\n</code></pre></li>\n</ol>\n\n<p>Graphs (performance tests depending on map size)</p>\n\n<p><a href="https://i.stack.imgur.com/17VGh.png" rel="noreferrer"><img src="https://i.stack.imgur.com/17VGh.png" alt="Enter image description here"></a></p>\n\n<p>Table (perfomance tests depending on map size)</p>\n\n<pre><code>          100     600      1100     1600     2100\ntest10    0.333    1.631    2.752    5.937    8.024\ntest3     0.309    1.971    4.147    8.147   10.473\ntest6     0.372    2.190    4.470    8.322   10.531\ntest1     0.405    2.237    4.616    8.645   10.707\ntest2     0.376    2.267    4.809    8.403   10.910\ntest7     0.473    2.448    5.668    9.790   12.125\ntest9     0.565    2.830    5.952   13.220   16.965\ntest4     0.808    5.012    8.813   13.939   17.407\ntest5     0.810    5.104    8.533   14.064   17.422\ntest8     5.173   12.499   17.351   24.671   30.403\n</code></pre>\n\n<p>All tests are on <a href="https://github.com/Vedenin/useful-java-links/blob/master/helloworlds/5.0-other-examples/src/main/java/other_examples/IterateThroughHashMapTest.java" rel="noreferrer">GitHub</a>.</p>\n'}, {'answer_id': 36591840, 'author': 'Sajad NasiriNezhad', 'author_id': 4533984, 'author_profile': 'https://Stackoverflow.com/users/4533984', 'pm_score': 4, 'selected': False, 'text': '<pre><code>           //Functional Oprations\n            Map&lt;String, String&gt; mapString = new HashMap&lt;&gt;();\n            mapString.entrySet().stream().map((entry) -&gt; {\n                String mapKey = entry.getKey();\n                return entry;\n            }).forEach((entry) -&gt; {\n                String mapValue = entry.getValue();\n            });\n\n            //Intrator\n            Map&lt;String, String&gt; mapString = new HashMap&lt;&gt;();\n            for (Iterator&lt;Map.Entry&lt;String, String&gt;&gt; it = mapString.entrySet().iterator(); it.hasNext();) {\n                Map.Entry&lt;String, String&gt; entry = it.next();\n                String mapKey = entry.getKey();\n                String mapValue = entry.getValue();\n            }\n\n            //Simple for loop\n            Map&lt;String, String&gt; mapString = new HashMap&lt;&gt;();\n            for (Map.Entry&lt;String, String&gt; entry : mapString.entrySet()) {\n                String mapKey = entry.getKey();\n                String mapValue = entry.getValue();\n\n            }\n</code></pre>\n'}, {'answer_id': 40260450, 'author': 'Witold Kaczurba', 'author_id': 6931119, 'author_profile': 'https://Stackoverflow.com/users/6931119', 'pm_score': 5, 'selected': False, 'text': '<p>The ordering will always depend on the specific map implementation.\nUsing Java\xa08 you can use either of these:</p>\n<pre><code>map.forEach((k,v) -&gt; { System.out.println(k + &quot;:&quot; + v); });\n</code></pre>\n<p>Or:</p>\n<pre><code>map.entrySet().forEach((e) -&gt; {\n            System.out.println(e.getKey() + &quot; : &quot; + e.getValue());\n        });\n</code></pre>\n<p>The result will be the same (same order). The entrySet backed by the map so you are getting the same order. The second one is handy as it allows you to use lambdas, e.g. if you want only to print only Integer objects that are greater than 5:</p>\n<pre><code>map.entrySet()\n    .stream()\n    .filter(e-&gt; e.getValue() &gt; 5)\n    .forEach(System.out::println);\n</code></pre>\n<p>The code below shows iteration through LinkedHashMap and normal HashMap (example). You will see difference in the order:</p>\n<pre><code>public class HMIteration {\n\n\n    public static void main(String[] args) {\n        Map&lt;Object, Object&gt; linkedHashMap = new LinkedHashMap&lt;&gt;();\n        Map&lt;Object, Object&gt; hashMap = new HashMap&lt;&gt;();\n\n        for (int i=10; i&gt;=0; i--) {\n            linkedHashMap.put(i, i);\n            hashMap.put(i, i);\n        }\n\n        System.out.println(&quot;LinkedHashMap (1): &quot;);\n        linkedHashMap.forEach((k,v) -&gt; { System.out.print(k + &quot; (#=&quot;+k.hashCode() + &quot;):&quot; + v + &quot;, &quot;); });\n\n        System.out.println(&quot;\\nLinkedHashMap (2): &quot;);\n\n        linkedHashMap.entrySet().forEach((e) -&gt; {\n            System.out.print(e.getKey() + &quot; : &quot; + e.getValue() + &quot;, &quot;);\n        });\n\n\n        System.out.println(&quot;\\n\\nHashMap (1): &quot;);\n        hashMap.forEach((k,v) -&gt; { System.out.print(k + &quot; (#:&quot;+k.hashCode() + &quot;):&quot; + v + &quot;, &quot;); });\n\n        System.out.println(&quot;\\nHashMap (2): &quot;);\n\n        hashMap.entrySet().forEach((e) -&gt; {\n            System.out.print(e.getKey() + &quot; : &quot; + e.getValue() + &quot;, &quot;);\n        });\n    }\n}\n</code></pre>\n<p>Output:</p>\n<pre><code>LinkedHashMap (1):\n10 (#=10):10, 9 (#=9):9, 8 (#=8):8, 7 (#=7):7, 6 (#=6):6, 5 (#=5):5, 4 (#=4):4, 3 (#=3):3, 2 (#=2):2, 1 (#=1):1, 0 (#=0):0,\nLinkedHashMap (2):\n10 : 10, 9 : 9, 8 : 8, 7 : 7, 6 : 6, 5 : 5, 4 : 4, 3 : 3, 2 : 2, 1 : 1, 0 : 0,\nHashMap (1):\n0 (#:0):0, 1 (#:1):1, 2 (#:2):2, 3 (#:3):3, 4 (#:4):4, 5 (#:5):5, 6 (#:6):6, 7 (#:7):7, 8 (#:8):8, 9 (#:9):9, 10 (#:10):10,\nHashMap (2):\n0 : 0, 1 : 1, 2 : 2, 3 : 3, 4 : 4, 5 : 5, 6 : 6, 7 : 7, 8 : 8, 9 : 9, 10 : 10,\n</code></pre>\n'}, {'answer_id': 43247492, 'author': 'Rupendra Sharma', 'author_id': 1706743, 'author_profile': 'https://Stackoverflow.com/users/1706743', 'pm_score': 3, 'selected': False, 'text': '<pre><code>package com.test;\n\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.Map;\nimport java.util.Map.Entry;\nimport java.util.Set;\n\npublic class Test {\n\n    public static void main(String[] args) {\n        Map&lt;String, String&gt; map = new HashMap&lt;String, String&gt;();\n        map.put("ram", "ayodhya");\n        map.put("krishan", "mathura");\n        map.put("shiv", "kailash");\n\n        System.out.println("********* Keys *********");\n        Set&lt;String&gt; keys = map.keySet();\n        for (String key : keys) {\n            System.out.println(key);\n        }\n\n        System.out.println("********* Values *********");\n        Collection&lt;String&gt; values = map.values();\n        for (String value : values) {\n            System.out.println(value);\n        }\n\n        System.out.println("***** Keys and Values (Using for each loop) *****");\n        for (Map.Entry&lt;String, String&gt; entry : map.entrySet()) {\n            System.out.println("Key: " + entry.getKey() + "\\t Value: "\n                    + entry.getValue());\n        }\n\n        System.out.println("***** Keys and Values (Using while loop) *****");\n        Iterator&lt;Entry&lt;String, String&gt;&gt; entries = map.entrySet().iterator();\n        while (entries.hasNext()) {\n            Map.Entry&lt;String, String&gt; entry = (Map.Entry&lt;String, String&gt;) entries\n                    .next();\n            System.out.println("Key: " + entry.getKey() + "\\t Value: "\n                    + entry.getValue());\n        }\n\n        System.out\n                .println("** Keys and Values (Using java 8 using lambdas )***");\n        map.forEach((k, v) -&gt; System.out\n                .println("Key: " + k + "\\t value: " + v));\n    }\n}\n</code></pre>\n'}, {'answer_id': 47122590, 'author': 'shivampip', 'author_id': 6759926, 'author_profile': 'https://Stackoverflow.com/users/6759926', 'pm_score': 4, 'selected': False, 'text': '<p>Iterating a <a href="https://docs.oracle.com/javase/10/docs/api/java/util/Map.html" rel="noreferrer">Map</a> is very easy. </p>\n\n<pre><code>for(Object key: map.keySet()){\n   Object value= map.get(key);\n   //Do your stuff\n}\n</code></pre>\n\n<p>For instance, you have a <code>Map&lt;String, int&gt; data;</code></p>\n\n<pre><code>for(Object key: data.keySet()){\n  int value= data.get(key);\n}\n</code></pre>\n'}, {'answer_id': 47256829, 'author': 'Utpal Kumar', 'author_id': 4745890, 'author_profile': 'https://Stackoverflow.com/users/4745890', 'pm_score': 4, 'selected': False, 'text': '<p>There are a lot of ways to do this. Below is a few simple steps:</p>\n\n<p>Suppose you have one Map like:</p>\n\n<pre><code>Map&lt;String, Integer&gt; m = new HashMap&lt;String, Integer&gt;();\n</code></pre>\n\n<p>Then you can do something like the below to iterate over map elements.</p>\n\n<pre><code>// ********** Using an iterator ****************\nIterator&lt;Entry&lt;String, Integer&gt;&gt; me = m.entrySet().iterator();\nwhile(me.hasNext()){\n    Entry&lt;String, Integer&gt; pair = me.next();\n    System.out.println(pair.getKey() + ":" + pair.getValue());\n}\n\n// *********** Using foreach ************************\nfor(Entry&lt;String, Integer&gt; me : m.entrySet()){\n    System.out.println(me.getKey() + " : " + me.getValue());\n}\n\n// *********** Using keySet *****************************\nfor(String s : m.keySet()){\n    System.out.println(s + " : " + m.get(s));\n}\n\n// *********** Using keySet and iterator *****************\nIterator&lt;String&gt; me = m.keySet().iterator();\nwhile(me.hasNext()){\n    String key = me.next();\n    System.out.println(key + " : " + m.get(key));\n}\n</code></pre>\n'}, {'answer_id': 49885402, 'author': 'ABHAY JOHRI', 'author_id': 7369238, 'author_profile': 'https://Stackoverflow.com/users/7369238', 'pm_score': 4, 'selected': False, 'text': '<p>Use Java 8:</p>\n\n<pre><code>map.entrySet().forEach(entry -&gt; System.out.println(entry.getValue()));\n</code></pre>\n'}, {'answer_id': 49921231, 'author': 'bluehallu', 'author_id': 512907, 'author_profile': 'https://Stackoverflow.com/users/512907', 'pm_score': 5, 'selected': False, 'text': '<p>Most compact with Java 8:</p>\n\n<pre><code>map.entrySet().forEach(System.out::println);\n</code></pre>\n'}, {'answer_id': 50153908, 'author': 'Taras Melnyk', 'author_id': 4813777, 'author_profile': 'https://Stackoverflow.com/users/4813777', 'pm_score': 6, 'selected': False, 'text': '<p>With <strong>Java 8</strong>, you can iterate Map using forEach and lambda expression,</p>\n\n<pre><code>map.forEach((k, v) -&gt; System.out.println((k + ":" + v)));\n</code></pre>\n'}, {'answer_id': 53497541, 'author': 'anandchaugule', 'author_id': 5756557, 'author_profile': 'https://Stackoverflow.com/users/5756557', 'pm_score': 4, 'selected': False, 'text': '<p>An effective iterative solution over a Map is a <code>for</code> loop from Java 5 through Java 7. Here it is:</p>\n<pre><code>for (String key : phnMap.keySet()) {\n    System.out.println(&quot;Key: &quot; + key + &quot; Value: &quot; + phnMap.get(key));\n}\n</code></pre>\n<p>From Java 8 you can use a lambda expression to iterate over a Map. It is an enhanced <code>forEach</code></p>\n<pre><code>phnMap.forEach((k,v) -&gt; System.out.println(&quot;Key: &quot; + k + &quot; Value: &quot; + v));\n</code></pre>\n<p>If you want to write a conditional for lambda you can write it like this:</p>\n<pre><code>phnMap.forEach((k,v)-&gt;{\n    System.out.println(&quot;Key: &quot; + k + &quot; Value: &quot; + v);\n    if(&quot;abc&quot;.equals(k)){\n        System.out.println(&quot;Hello abc&quot;);\n    }\n});\n</code></pre>\n'}, {'answer_id': 56467159, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '<p>I like to concat a counter, then save the final value of the counter;</p>\n\n<pre><code>int counter = 0;\nHashMap&lt;String, String&gt; m = new HashMap&lt;String, String&gt;();\nfor(int i = 0;i&lt;items.length;i++)\n{\nm.put("firstname"+i, items.get(i).getFirstName());\ncounter = i;\n}\n\nm.put("recordCount",String.valueOf(counter));\n</code></pre>\n\n<p>Then when you want to retrieve:</p>\n\n<pre><code>int recordCount = Integer.parseInf(m.get("recordCount"));\nfor(int i =0 ;i&lt;recordCount;i++)\n{\nSystem.out.println("First Name :" + m.get("firstname"+i));\n}\n</code></pre>\n'}, {'answer_id': 57321787, 'author': 'Lova Chittumuri', 'author_id': 5256337, 'author_profile': 'https://Stackoverflow.com/users/5256337', 'pm_score': 3, 'selected': False, 'text': '<blockquote>\n  <p>Using  Java 7</p>\n</blockquote>\n\n<pre><code>Map&lt;String,String&gt; sampleMap = new HashMap&lt;&gt;();\nfor (sampleMap.Entry&lt;String,String&gt; entry : sampleMap.entrySet()) {\n    String key = entry.getKey();\n    String value = entry.getValue();\n\n    /* your Code as per the Business Justification  */\n\n}\n</code></pre>\n\n<blockquote>\n  <p>Using Java 8</p>\n</blockquote>\n\n<pre><code>Map&lt;String,String&gt; sampleMap = new HashMap&lt;&gt;();\n\nsampleMap.forEach((k, v) -&gt; System.out.println("Key is :  " + k + " Value is :  " + v));\n</code></pre>\n'}, {'answer_id': 58574145, 'author': 'Basil Bourque', 'author_id': 642706, 'author_profile': 'https://Stackoverflow.com/users/642706', 'pm_score': 5, 'selected': False, 'text': '<blockquote>\n  <p>If I have an object implementing the Map interface in Java and I wish to iterate over every pair contained within it, what is the most efficient way of going through the map?</p>\n</blockquote>\n\n<p>If efficiency of looping the keys is a priority for your app, then choose a <code>Map</code> implementation that maintains the keys in your desired order.</p>\n\n<blockquote>\n  <p>Will the ordering of elements depend on the specific map implementation that I have for the interface?</p>\n</blockquote>\n\n<p>Yes, absolutely. </p>\n\n<ul>\n<li>Some <code>Map</code> implementations promise a certain iteration order, others do not.</li>\n<li>Different implementations of <code>Map</code> maintain different ordering of the key-value pairs. </li>\n</ul>\n\n<p>See this table I created summarizing the various <code>Map</code> implementations bundled with Java 11. Specifically, notice the <em>iteration order</em> column. Click/tap to zoom.</p>\n\n<p><a href="https://i.stack.imgur.com/4z5Fb.png" rel="noreferrer"><img src="https://i.stack.imgur.com/4z5Fb.png" alt="Table of map implementations in Java 11, comparing their features"></a></p>\n\n<p>You can see there are <strong>four <code>Map</code> implementations maintaining an order</strong>:</p>\n\n<ul>\n<li><code>TreeMap</code></li>\n<li><code>ConcurrentSkipListMap</code> </li>\n<li><code>LinkedHashMap</code></li>\n<li><code>EnumMap</code></li>\n</ul>\n\n<h2><code>NavigableMap</code> interface</h2>\n\n<p>Two of those implement the <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/NavigableMap.html" rel="noreferrer"><code>NavigableMap</code></a> interface: <code>TreeMap</code> &amp; <code>ConcurrentSkipListMap</code>. </p>\n\n<p>The older <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/SortedMap.html" rel="noreferrer"><code>SortedMap</code></a> interface is effectively supplanted by the newer <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/NavigableMap.html" rel="noreferrer"><code>NavigableMap</code></a> interface. But you may find 3rd-party implementations implementing the older interface only.</p>\n\n<h2>Natural order</h2>\n\n<p>If you want a <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Map.html" rel="noreferrer"><code>Map</code></a> that keeps its pairs arranged by the “natural order” of the key, use <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/TreeMap.html" rel="noreferrer"><code>TreeMap</code></a> or <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/concurrent/ConcurrentSkipListMap.html" rel="noreferrer"><code>ConcurrentSkipListMap</code></a>. The term “natural order” means the class of the keys implements <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Comparable.html" rel="noreferrer"><code>Comparable</code></a>. The value returned by the <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Comparable.html#compareTo(T)" rel="noreferrer"><code>compareTo</code></a> method is used for comparison in sorting.</p>\n\n<h2>Custom order</h2>\n\n<p>If you want to specify a custom sorting routine for your keys to be used in maintaining a sorted order, pass a <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Comparator.html" rel="noreferrer"><code>Comparator</code></a> implementation appropriate to the class of your keys. Use either <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/TreeMap.html" rel="noreferrer"><code>TreeMap</code></a> or <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/concurrent/ConcurrentSkipListMap.html" rel="noreferrer"><code>ConcurrentSkipListMap</code></a>, passing your <code>Comparator</code>. </p>\n\n<h2>Original insertion order</h2>\n\n<p>If you want the pairs of your map to be kept in their original order in which you inserted them into the map, use <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/LinkedHashMap.html" rel="noreferrer"><code>LinkedHashMap</code></a>. </p>\n\n<h2>Enum-definition order</h2>\n\n<p>If you are using an enum such as <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/time/DayOfWeek.html" rel="noreferrer"><code>DayOfWeek</code></a> or <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/time/Month.html" rel="noreferrer"><code>Month</code></a> as your keys, use the <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/EnumMap.html" rel="noreferrer"><code>EnumMap</code></a> class. Not only is this class <em>highly</em> optimized to use very little memory and run very fast, it maintains your pairs in the order defined by the enum. For <code>DayOfWeek</code>, for example, the key of <code>DayOfWeek.MONDAY</code> will be first found when iterated, and the key of <code>DayOfWeek.SUNDAY</code> will be last.</p>\n\n<h2>Other considerations</h2>\n\n<p>In choosing a <code>Map</code> implementation, also consider:</p>\n\n<ul>\n<li>NULLs. Some implementations forbid/accept a NULL as key and/or value. </li>\n<li>Concurrency. If you are manipulating the map across threads, you must use an implementation that supports concurrency. Or wrap the map with <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Collections.html#synchronizedMap(java.util.Map)" rel="noreferrer"><code>Collections::synchronizedMap</code></a> (less preferable). </li>\n</ul>\n\n<p>Both of these considerations are covered in the graphic table above.</p>\n'}, {'answer_id': 59608364, 'author': 'Ali Akram', 'author_id': 4332316, 'author_profile': 'https://Stackoverflow.com/users/4332316', 'pm_score': 3, 'selected': False, 'text': '<h1><code>Map.forEach</code></h1>\n\n<p>What about simply using <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Map.html#forEach(java.util.function.BiConsumer)" rel="noreferrer"><code>Map::forEach</code></a> where both the key and the value are passed to your <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/function/BiConsumer.html" rel="noreferrer"><code>BiConsumer</code></a>?</p>\n\n<pre><code>map.forEach((k,v)-&gt;{\n    System.out.println(k+"-&gt;"+v);\n});\n</code></pre>\n'}, {'answer_id': 62378360, 'author': 'Younes El Ouarti', 'author_id': 3705861, 'author_profile': 'https://Stackoverflow.com/users/3705861', 'pm_score': 3, 'selected': False, 'text': '<p>Since Java 10, you can use local variable inference (a.k.a. "var") to make a lot of the already available answers less bloated. For example:</p>\n\n<pre class="lang-java prettyprint-override"><code>for (var entry : map.entrySet()) {\n    System.out.println(entry.getKey() + " : " + entry.getValue());\n}\n</code></pre>\n'}, {'answer_id': 63910874, 'author': 'Dubstep', 'author_id': 9363081, 'author_profile': 'https://Stackoverflow.com/users/9363081', 'pm_score': 2, 'selected': False, 'text': '<pre><code>Map&lt;String, String&gt; map = \nfor (Map.Entry&lt;String, String&gt; entry : map.entrySet()) {\n    MapKey = entry.getKey() \n    MapValue = entry.getValue();\n}\n</code></pre>\n'}, {'answer_id': 65670377, 'author': 'Badri Paudel', 'author_id': 9898251, 'author_profile': 'https://Stackoverflow.com/users/9898251', 'pm_score': 2, 'selected': False, 'text': '<p>You can search for the key and with the help of the key you can find the associated value of the map as map has <strong>unique key</strong>, see what happens when key is duplicate <a href="https://stackoverflow.com/a/20537942/9898251">here</a> or <a href="https://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html#put%28K,%20V%29" rel="nofollow noreferrer">here</a>.</p>\n<p>Demo map :</p>\n<pre><code> Map&lt;String, String&gt; map = new HashMap();\n  map.put(&quot;name&quot;, &quot;Name&quot;);\n  map.put(&quot;age&quot;, &quot;23&quot;);\n  map.put(&quot;address&quot;, &quot;NP&quot;);\n  map.put(&quot;faculty&quot;, &quot;BE&quot;);\n  map.put(&quot;major&quot;, &quot;CS&quot;);\n  map.put(&quot;head&quot;, &quot;MDK&quot;);\n \n</code></pre>\n<p>To get key only, you can use <code>map.keySet();</code> like this :</p>\n<pre><code>for(String key : map.keySet()) {\n      System.out.println(key);\n  }\n</code></pre>\n<p>To get value only , you can use <code>map.values();</code> like this:</p>\n<pre><code>      for(String value : map.values()) {\n      System.out.println(value);\n  }\n</code></pre>\n<p>To get both key and its value you still can use <code>map.keySet();</code> and get its corresponding value, like this :</p>\n<pre><code> //this prints the key value pair\n  for (String k : map.keySet()) {\n        System.out.println(k + &quot; &quot; + map.get(k) + &quot; &quot;);\n    }\n</code></pre>\n<p><code>map.get(key)</code> gives the value pointed by that key.</p>\n'}, {'answer_id': 69379440, 'author': 'anand krish', 'author_id': 2147814, 'author_profile': 'https://Stackoverflow.com/users/2147814', 'pm_score': 4, 'selected': False, 'text': '<p>These are all the possible ways of iterating HashMap.</p>\n<pre><code>HashMap&lt;Integer,String&gt; map=new HashMap&lt;Integer,String&gt;();\n    map.put(1,&quot;David&quot;);  //Adding elements in Map\n    map.put(2,&quot;John&quot;);\n    map.put(4,&quot;Samyuktha&quot;);\n    map.put(3,&quot;jasmin&quot;);\n    System.out.println(&quot;Iterating Hashmap...&quot;);\n\n    //way 1 (java 8 Method)\n    map.forEach((key, value) -&gt; {\n        System.out.println(key+&quot; : &quot;+ value);\n    });\n\n    //way 2 (java 7 Method)\n    for(Map.Entry me : map.entrySet()){\n        System.out.println(me.getKey()+&quot; &quot;+me.getValue());\n    }\n\n    //way 3 (Legacy way to iterate HashMap)\n    Iterator iterator = map.entrySet().iterator();//map.keySet().iterator()\n    while (iterator.hasNext())\n    {\n        Map.Entry me =(Map.Entry)iterator.next();\n        System.out.println(me.getKey()+&quot; : &quot;+ me.getValue());\n    }\n    \n}\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/46898', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4807/']