How to loop a Map in Java

Here are few ways to loop or iterate a Map or HashMap in Java.

package com.mkyong;
 
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
 
public class LoopMap {
 
  public static void main(String[] args) {
 
	// initial a Map
	Map<String, String> map = new HashMap<String, String>();
	map.put("1", "Jan");
	map.put("2", "Feb");
	map.put("3", "Mar");
	map.put("4", "Apr");
	map.put("5", "May");
	map.put("6", "Jun");
 
	System.out.println("Example 1...");
	// Map -> Set -> Iterator -> Map.Entry -> troublesome
	Iterator iterator = map.entrySet().iterator();
	while (iterator.hasNext()) {
		Map.Entry mapEntry = (Map.Entry) iterator.next();
		System.out.println("The key is: " + mapEntry.getKey()
			+ ",value is :" + mapEntry.getValue());
	}
 
	System.out.println("Example 2...");
	// more elegant way
	for (Map.Entry<String, String> entry : map.entrySet()) {
		System.out.println("Key : " + entry.getKey() + " Value : "
			+ entry.getValue());
	}
 
	System.out.println("Example 3...");
	// weired way, but works anyway
	for (Object key : map.keySet()) {
		System.out.println("Key : " + key.toString() + " Value : "
			+ map.get(key));
	}
 
  }
 
}

Output

Example 1...
The key is: 3,value is :Mar
The key is: 2,value is :Feb
The key is: 1,value is :Jan
The key is: 6,value is :Jun
The key is: 5,value is :May
The key is: 4,value is :Apr
Example 2...
Key : 3 Value : Mar
Key : 2 Value : Feb
Key : 1 Value : Jan
Key : 6 Value : Jun
Key : 5 Value : May
Key : 4 Value : Apr
Example 3...
Key : 3 Value : Mar
Key : 2 Value : Feb
Key : 1 Value : Jan
Key : 6 Value : Jun
Key : 5 Value : May
Key : 4 Value : Apr
Note
Which ways to go? It’s your personal preference.
Tags :

About the Author

mkyong
Founder of Mkyong.com and HostingCompass.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

  • mukesh

    Thank you very mutch…

  • mohd5912

    please how add string[] to Map this is my code but not working

    Map entry;
    List<Map> data;
    String[] array1;
    String[] array2;
    for (int i=0;i < arraybooks.length;i++)
    {
    for (int i2=0;i2 < arrayconts.length;i2++)
    {
    entry = new HashMap();
    entry.put(“Title”, array1[i]);
    entry.put(“Author”,arra2[i2]);
    data.add(entry);
    }
    }

  • Pingback: How to read and parse CSV file in Java()

  • Pingback: replacing few keywords with corresponding operators()

  • kiran

    Thanks for Providing…

  • http://searchingwhat.com mintu

    you can use this
    HashMap<String, List> map = new HashMap<String, List>();
    map.put(“key1″, new ArrayList());
    map.get(“key1″).add(“val”);

    for (List value : map.values()) {
    System.out.println(value.contains(“val”));
    }
    Bye

  • https://twitter.com/a_podkutin Alexander Podkutin

    Thank you for simple working examples, now I understand Map interface much better.

  • merve

    thanks, chic solutions

  • Nate

    Thank you for this! I was looking for a straight forward example you have delivered!

  • Sekhar

    Suppose i have data like

            map.put(&quot;1&quot;, &quot;Jhon[roll=2,standard=4,mark=54]&quot;);
    	map.put(&quot;2&quot;, &quot;Jack[roll=3,standard=4,mark=84]&quot;);
    	map.put(&quot;3&quot;, &quot;Will[roll=4,standard=4,mark=34]&quot;);
    	map.put(&quot;4&quot;, &quot;Stefan[roll=5,standard=4,mark=14]&quot;);

    So can any one tell me how to get the data as below
    ——————————
    JHON
    Roll – 2
    Mark -54
    Standard-4
    ——————————
    so i want to get all those data in the above format. please help.

  • Pingback: Compare Maps – Java | Tsetso's Stuff()

  • http://www.nikoslianeris.gr nikos lianeris

    Although I used to use the while edition in my first projects I agree that the for-each edition is indeed more elegant and efficient

  • http://www.wzq110120.51.com Chinese dragon

    fuck,I’t so simple………….

  • John

    Your ‘weired way’ is a bad idea, since you’ll be doing a lot of unnecessary hashtable lookups by using map.get while iterating.
    See: http://findbugs.sourceforge.net/bugDescriptions.html#WMI_WRONG_MAP_ITERATOR

    • Som3

      Why is it so bad ? Evaluating hash code is supposed to be cheap.
      Also makes more sense when you are grouping Objects for instance Map<String,List>).

      • nickers

        It is cheap, but not free. I gives you extra complexity to your code. You will feel it every time, when you will have to process 100 messages per second.

        That is not too much in fact. Try to process your emails for some strange service. I have 5k mails. Lets assume first ‘for’ (from this blog entry) gives extra 0,1 second. Now do it for all your users (assume 10k). It is 1k seconds extra ~16 minutes. It is all about scale!

        • Peter Lawrey

          Using entrySet() is slightly safer, esp for debugging, as it will is give you matching key/values even if a) hashCode/equals are broken, or more likely b) the map is modified while you are using it.

  • Vic

    one more :)

    for (Iterator it = fromPackage.iterator(); it.hasNext();) {
    Descriptor resourse = it.next();
    ………
    }