{"id":1586,"date":"2017-03-22T13:16:46","date_gmt":"2017-03-22T07:46:46","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=1586"},"modified":"2017-03-29T10:09:39","modified_gmt":"2017-03-29T04:39:39","slug":"java-efficiently-iterate-entry-map","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/java-efficiently-iterate-entry-map\/","title":{"rendered":"JAVA &#8211; How to efficiently iterate over each Entry in a Map"},"content":{"rendered":"<h4 id=\"java-map-interface\"><span style=\"color: #800000;\"><b>Java Map Interface<\/b><\/span><\/h4>\n<ul>\n<li>A map contains values on the basis of key i.e. key and value pair. Each key and value pair is known as an entry. Map contains only unique keys.<\/li>\n<li>Map is useful if we have to search, update or delete elements on the basis of key.<\/li>\n<\/ul>\n<h4 id=\"map-entry-interface\"><span style=\"color: #ff6600;\"><b>Map.Entry<\/b><b> Interface<\/b><\/span><\/h4>\n<ul>\n<li>Entry is the sub interface of Map.<\/li>\n<li>So we will be accessed it by Map.Entry name.<\/li>\n<li>It provides methods to get key and value.<\/li>\n<\/ul>\n<h4 id=\"how-to-iterate-over-a-map-in-java\"><span style=\"color: #000000;\"><b>How to Iterate Over a Map in Java<\/b><\/span><\/h4>\n<ul>\n<li>There are several ways of iterating over a Map in Java.<\/li>\n<li>Since all maps in Java implement Map interface, following techniques will work for any map implementation (HashMap, TreeMap, LinkedHashMap, Hashtable, etc.)<\/li>\n<\/ul>\n<ul>\n<ul>\n<li><b>Iterating over entries using For-Each loop.<\/b><\/li>\n<li><b>Iterating over keys or values using For-Each loop.<\/b><\/li>\n<li><b>Iterating using Iterator.<\/b><\/li>\n<li><b>Iterating over keys and searching for values (inefficient).<\/b><\/li>\n<\/ul>\n<\/ul>\n<h4 id=\"method-1-iterating-over-entries-using-for-each-loop\"><span style=\"color: #000000;\"><b>Method 1: Iterating over entries using For-Each loop.<\/b><\/span><\/h4>\n<ul>\n<li>This is the most common method and is preferable in most cases.<\/li>\n<li>It should be used if we need both map keys and values in the loop.<\/li>\n<\/ul>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">java code<\/span> <\/div> <pre class=\"language-java code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-java code-embed-code\">Map&lt;Integer, Integer&gt; map = new HashMap&lt;Integer, Integer&gt;();<br\/>for (Map.Entry&lt;Integer, Integer&gt; entry : map.entrySet()) <br\/>{<br\/>    System.out.println(&quot;Key = &quot; + entry.getKey() + &quot;, Value = &quot; + entry.getValue());<br\/>}<\/code><\/pre> <\/div>\n<h4 id=\"note\"><span style=\"color: #000000;\"><b>Note:<\/b><\/span><\/h4>\n<ul>\n<li><span style=\"color: #000000;\">For-Each loop was introduced in Java 5, so this method is working only in newer versions of the language.<\/span><\/li>\n<li><span style=\"color: #000000;\">In addition For-Each loop will throw NullPointerException if we try to iterate over a map that is null, so before iterating we should always check for null references.<\/span><\/li>\n<\/ul>\n<h4 id=\"method-2-iterating-over-keys-or-values-using-for-each-loop\"><span style=\"color: #000000;\"><b>Method 2: Iterating over keys or values using For-Each loop.<\/b><\/span><\/h4>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">java code<\/span> <\/div> <pre class=\"language-java code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-java code-embed-code\">Map&lt;Integer, Integer&gt; map = new HashMap&lt;Integer, Integer&gt;();<br\/><br\/>\/\/iterating over keys only<br\/>for (Integer key : map.keySet()) <br\/>{<br\/>    System.out.println(&quot;Key = &quot; + key);<br\/>}<br\/><br\/>\/\/iterating over values only<br\/>for (Integer value : map.values()) <br\/>{<br\/>    System.out.println(&quot;Value = &quot; + value);<br\/>}<\/code><\/pre> <\/div>\n[ad type=&#8221;banner&#8221;]\n<ul>\n<li>If we need only keys or values from the map, we can iterate over keySet or values instead of entrySet.<\/li>\n<li>This method gives a slight performance advantage over entrySet iteration (about 10% faster).<\/li>\n<\/ul>\n<h4 id=\"method-3-iterating-using-iterator\"><span style=\"color: #000000;\"><b>Method 3: Iterating using Iterator.<\/b><\/span><\/h4>\n<h4 id=\"using-generics\"><span style=\"color: #000000;\">Using Generics:<\/span><\/h4>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">java code<\/span> <\/div> <pre class=\"language-java code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-java code-embed-code\">Map&lt;Integer, Integer&gt; map = new HashMap&lt;Integer, Integer&gt;();<br\/>Iterator&lt;Map.Entry&lt;Integer, Integer&gt;&gt; entries = map.entrySet().iterator();<br\/>while (entries.hasNext()) <br\/>{<br\/>    Map.Entry&lt;Integer, Integer&gt; entry = entries.next();<br\/>    System.out.println(&quot;Key = &quot; + entry.getKey() + &quot;, Value = &quot; + entry.getValue());<br\/>}<\/code><\/pre> <\/div>\n<h4 id=\"without-generics\"><span style=\"color: #000000;\">Without Generics:<\/span><\/h4>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">java code<\/span> <\/div> <pre class=\"language-java code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-java code-embed-code\">Map map = new HashMap();<br\/>Iterator entries = map.entrySet().iterator();<br\/>while (entries.hasNext()) <br\/>{<br\/>    Map.Entry entry = (Map.Entry) entries.next();<br\/>    Integer key = (Integer)entry.getKey();<br\/>    Integer value = (Integer)entry.getValue();<br\/>    System.out.println(&quot;Key = &quot; + key + &quot;, Value = &quot; + value);<br\/>}<\/code><\/pre> <\/div>\n<ul>\n<li>Initially, it is the only way to iterate over a map in older versions of Java.<\/li>\n<li>The other important feature is that it is the only method that allows to remove entries from the map during iteration by calling iterator.remove().<\/li>\n<li>If we try to do this during For-Each iteration we will get &#8220;unpredictable results&#8221; according to Javadoc.<\/li>\n<li>From a performance point of view this method is equal to a For-Each iteration.<\/li>\n<\/ul>\n<h4 id=\"method-4-iterating-over-keys-and-searching-for-values-inefficient\"><span style=\"color: #000000;\"><b>Method 4: Iterating over keys and searching for values (inefficient).<\/b><\/span><\/h4>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">java code<\/span> <\/div> <pre class=\"language-java code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-java code-embed-code\">Map&lt;Integer, Integer&gt; map = new HashMap&lt;Integer, Integer&gt;();<br\/>for (Integer key : map.keySet()) <br\/>{<br\/>    Integer value = map.get(key);<br\/>    System.out.println(&quot;Key = &quot; + key + &quot;, Value = &quot; + value);<br\/>}<\/code><\/pre> <\/div>\n<ul>\n<li>This might look like a cleaner alternative for method 1, but in practice it is slow and inefficient as getting values by a key might be time-consuming.<\/li>\n<li>\u00a0If we have FindBugs installed, it will detect this and warn about inefficient iteration.<\/li>\n<\/ul>\n<h4 id=\"best-way-to-iterate-over-hashmap-in-java\"><span style=\"color: #000000;\"><b>Best way to Iterate over <\/b><b>HashMap<\/b><b> in Java<\/b><\/span><\/h4>\n<ul>\n<li>Here is the code example of Iterating over any Map class in Java (e.g. Hashtable or LinkedHashMap)<\/li>\n<li>we used HashMap for iteration purpose, we can apply same technique to other Map implementations.<\/li>\n<li>Since we are only using methods from java.uti.Map interface, solution is extensible to all kinds of Map in Java.<\/li>\n<li>We will use Java 1.5 foreach loop and Iterating over each Map.Entry object, which we get by calling Map.entrySet() method.<\/li>\n<li>Using Generics to avoid type casting.<\/li>\n<\/ul>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">java code<\/span> <\/div> <pre class=\"language-java code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-java code-embed-code\">for(Map.Entry&lt;Integer, String&gt; entry : map.entrySet())<br\/>{ <br\/>System.out.printf(&quot;Key : %s and Value: %s %n&quot;, entry.getKey(), entry.getValue()); <br\/>}<\/code><\/pre> <\/div>\n[ad type=&#8221;banner&#8221;]\n<ul>\n<li>This above code has one drawback, we can not remove entries without risking ConcurrentModificationException.<\/li>\n<\/ul>\n<h4 id=\"removing-entries-from-map-in-java\"><span style=\"color: #000000;\"><b>Removing Entries from Map in Java: <\/b><\/span><\/h4>\n<ul>\n<li>One reason for iterating over Map is removing selected key value pairs from Map.<\/li>\n<li>This is a general Map requirement and holds true for any kind of Map e.g. HashMap, Hashtable, LinkedHashMap or even relatively new ConcurrentHashMap.<\/li>\n<li>When we use foreach loop, it internally translated into Iterator code, but without explicit handle to Iterator, we just can not remove entries during Iteration. If you do,\u00a0 your Iterator may throw ConcurrentModificationException.<\/li>\n<li>To avoid this, we need to use explicit Iterator and while loop for traversal. We will still use entrySet() for performance reason, but we will use Iterator&#8217;s remove() method for deleting entries from Map.<\/li>\n<\/ul>\n<p><strong>Here code example\u00a0 to remove key values from HashMap in Java:<\/strong><\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">java code<\/span> <\/div> <pre class=\"language-java code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-java code-embed-code\">Iterator&lt;Map.Entry&lt;Integer, String&gt;&gt; iterator = map.entrySet().iterator();<br\/>while(iterator.hasNext())<br\/>{<br\/>   Map.Entry&lt;Integer, String&gt; entry = iterator.next();<br\/>   System.out.printf(&quot;Key : %s and Value: %s %n&quot;, entry.getKey(), entry.getValue());<br\/>   iterator.remove(); \/\/ right way to remove entries from Map, <br\/>                      \/\/ avoids ConcurrentModificationException<br\/>}<\/code><\/pre> <\/div>\n<p>we are using\u00a0<strong>remove()<\/strong>\u00a0method from Iterator and not from\u00a0<strong>java.util.Map<\/strong>, which accepts a key object. This code is safe from\u00a0<strong>ConcurrentModificationException.<\/strong><\/p>\n<h4 id=\"removing-entries-from-map-in-java-2\"><span style=\"color: #000000;\"><b>Removing Entries from Map in Java: <\/b><\/span><\/h4>\n<ul>\n<li>One reason for iterating over Map is removing selected key value pairs from Map.<\/li>\n<li>This is a general Map requirement and holds true for any kind of Map (e.g. HashMap, Hashtable, LinkedHashMap or even relatively new ConcurrentHashMap)<\/li>\n<li>When we use foreach loop, it internally translated into Iterator code, but without explicit handle to Iterator, we just can not remove entries during Iteration. If we do,\u00a0 our Iterator may throw ConcurrentModificationException.<\/li>\n<li>To avoid this, we need to use explicit Iterator and while loop for traversal. We will still use entrySet() for performance reason, but we will use Iterator&#8217;s remove() method for deleting entries from Map.<\/li>\n<\/ul>\n<h4 id=\"hashmap-iterator-example\"><span style=\"color: #000000;\"><b>HashMap<\/b><b> Iterator Example<\/b><\/span><\/h4>\n<p>Here is complete code example, combining both approaches for iterating over HashMap in Java.<\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">java code<\/span> <\/div> <pre class=\"language-java code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-java code-embed-code\">import java.util.HashMap;<br\/>import java.util.Iterator; <br\/>import java.util.Map;<br\/> \/**<br\/> * Best way to iterate over Map in Java, including any implementation e.g. <br\/>* HashMap, TreeMap, LinkedHashMap, ConcurrentHashMap and Hashtable.<br\/> * Java 1.5 foreach loop is most elegant and combined with entry set also<br\/> * gives best performance, but not suitable for removing entries, as you don&#039;t have<br\/> * reference to internal Iterator. <br\/>* * Only way to remove entries from Map without throwing ConcurrentModificationException<br\/> * is to use Iterator and while loop. * *\/<br\/>public class WikitechyHashMapIteratorExample <br\/>{<br\/><br\/>    public static void main(String args[]) {<br\/>     <br\/>        \/\/ Initializing HashMap with some key values<br\/>        Map&lt;Integer, String&gt; map = new HashMap&lt;Integer, String&gt;();<br\/>        map.put(1, &quot;Core Java&quot;);<br\/>        map.put(2, &quot;Java SE&quot;);<br\/>        map.put(3, &quot;Java ME&quot;);<br\/>        map.put(4, &quot;Java EE&quot;);<br\/>        map.put(5, &quot;Java FX&quot;);<br\/>       <br\/>        \/\/ Iterate over HashMap using foreach loop<br\/>        System.out.println(&quot;Java 1.5 foreach loop provides most elegant<br\/>                             way to iterate over HashMap in Java&quot;);<br\/>        for(Map.Entry&lt;Integer, String&gt; entry : map.entrySet()){<br\/>            System.out.printf(&quot;Key : %s and Value: %s %n&quot;, entry.getKey(),<br\/>                                                           entry.getValue());<br\/>        }<br\/>\/\/ Better way to loop over HashMap, if you want to remove entry<br\/>        System.out.println(&quot;Use Iterator and while loop, if you want <br\/>                              to remove entries from HashMap during iteration&quot;);<br\/>        Iterator&lt;Map.Entry&lt;Integer, String&gt;&gt; iterator = map.entrySet().iterator();<br\/>        while(iterator.hasNext())<br\/>{<br\/>            Map.Entry&lt;Integer, String&gt; entry = iterator.next();<br\/>            System.out.printf(&quot;Key : %s and Value: %s %n&quot;, entry.getKey(), <br\/>                                                           entry.getValue());<br\/>            iterator.remove(); \/\/ right way to remove entries from Map, <br\/>                               \/\/ avoids ConcurrentModificationException<br\/>        }<br\/>    }    <br\/>  <br\/>}<\/code><\/pre> <\/div>\n<h4 id=\"output\"><span style=\"color: #000000;\"><b>Output:<\/b><\/span><\/h4>\n<blockquote><p><strong>Java 1.5 foreach loop provides most elegant way to iterate over HashMap in Java<\/strong><\/p>\n<p><strong>Key : 1 and Value: Core Java<\/strong><\/p>\n<p><strong>Key : 2 and Value: Java SE<\/strong><\/p>\n<p><strong>Key : 3 and Value: Java ME<\/strong><\/p>\n<p><strong>Key : 4 and Value: Java EE<\/strong><\/p>\n<p><strong>Key : 5 and Value: Java FX<\/strong><\/p>\n<p><strong>Use Iterator and while loop, if you want to remove entries from HashMap during iteration<\/strong><\/p>\n<p><strong>Key : 1 and Value: Core Java<\/strong><\/p>\n<p><strong>Key : 2 and Value: Java SE<\/strong><\/p>\n<p><strong>Key : 3 and Value: Java ME<\/strong><\/p>\n<p><strong>Key : 4 and Value: Java EE<\/strong><\/p>\n<p><strong>Key : 5 and Value: Java FX<\/strong><\/p><\/blockquote>\n[ad type=&#8221;banner&#8221;]\n","protected":false},"excerpt":{"rendered":"<p>Java Map Interface A map contains values on the basis of key i.e. key and value pair. Each key and value pair is known as an entry. Map contains only unique keys. Map is useful if we have to search, update or delete elements on the basis of key. Map.Entry Interface Entry is the sub [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2139],"tags":[3232,3230,2671,2861,3223,3231,3221,3225,3220,2858,3224,2859,3229,2863,3219,3226,3218,3227,2866,3222,3228],"class_list":["post-1586","post","type-post","status-publish","format-standard","hentry","category-java","tag-4-different-ways-to-iterate-through-a-map-in-java","tag-efficiently-iterating-over-dictionary-list-values-by-skipping-missing-values-python-3","tag-for-each-over-an-array-in-javascript","tag-hashmap-entryset","tag-how-can-i-initialise-a-static-map","tag-how-do-you-iterate-over-a-hash-map-of-arraylists-of-string","tag-how-to-iterate-set-in-java","tag-how-to-loop-through-a-c-map-of-maps","tag-iterate-list-in-java","tag-iterate-through-map-c","tag-iterating-over-dictionaries-using-for-loops-in-python","tag-java-8-iterate-map","tag-java-efficient-iterating-over-char","tag-java-map-entryset","tag-java-map-iterator-remove","tag-java-most-efficient-method-to-iterate-over-all-elements-in-a-org-w3c-dom-document","tag-map-foreach-java","tag-skip-items-while-iterating-over-a-long-list","tag-ways-to-iterate-over-a-list-in-java","tag-what-is-the-best-way-to-iterate-over-a-dictionary-in-c","tag-whats-more-efficient"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/1586","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/comments?post=1586"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/1586\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=1586"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=1586"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=1586"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}