How to loop a Map in Java

This code snippet shows you how to loop a Map in Java.


	Map<String, String> map = new HashMap<>();
	map.put("1", "Jan");
	map.put("2", "Feb");
	map.put("3", "Mar");
	
	// classic way, loop a Map
	for (Map.Entry<String, String> entry : map.entrySet()) {
		System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
	}
		
	//Java 8 only, forEach and Lambda
	map.forEach((k,v)->System.out.println("Key : " + k + " Value : " + v));

Output


    Key : 1 Value :Jan
    Key : 2 Value :Feb
    Key : 3 Value :Mar

    Key : 1 Value :Jan
    Key : 2 Value :Feb
    Key : 3 Value :Mar

1. Examples

Different ways to loop a Map

LoopMap.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<>();
        map.put("1", "Jan");
        map.put("2", "Feb");
        map.put("3", "Mar");
        map.put("4", "Apr");
        map.put("5", "May");
        map.put("6", "Jun");

        // Standard classic way, recommend!
        System.out.println("\nExample 1...");
        for (Map.Entry<String, String> entry : map.entrySet()) {
            System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
        }

        // Java 8, forEach and Lambda. recommend!
        System.out.println("\nExample 2...");
        map.forEach((k, v) -> System.out.println("Key : " + k + " Value : " + v));

        // Map -> Set -> Iterator -> Map.Entry -> troublesome, don't use, just for fun
        System.out.println("\nExample 3...");
        Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, String> entry = iterator.next();
            System.out.println("Key : " + entry.getKey() + " Value :" + entry.getValue());
        }

        // weired, but works anyway, don't use, just for fun
        System.out.println("\nExample 4...");
        for (Object key : map.keySet()) {
            System.out.println("Key : " + key.toString() + " Value : " + map.get(key));
        }

    }

}

Output


Example 1...
Key : 1 Value : Jan
Key : 2 Value : Feb
Key : 3 Value : Mar
Key : 4 Value : Apr
Key : 5 Value : May
Key : 6 Value : Jun

Example 2...
Key : 1 Value : Jan
Key : 2 Value : Feb
Key : 3 Value : Mar
Key : 4 Value : Apr
Key : 5 Value : May
Key : 6 Value : Jun

Example 3...
Key : 1 Value :Jan
Key : 2 Value :Feb
Key : 3 Value :Mar
Key : 4 Value :Apr
Key : 5 Value :May
Key : 6 Value :Jun

Example 4...
Key : 1 Value : Jan
Key : 2 Value : Feb
Key : 3 Value : Mar
Key : 4 Value : Apr
Key : 5 Value : May
Key : 6 Value : Jun

2. Map Filtering

In Java 8, you can convert a Map into a Stream and filter it like this :


	map.entrySet().stream()
        .filter(x -> "Jan".equals(x.getValue()))
        .forEach( x -> System.out.println("Key : " + x.getKey() + " Value : " + x.getValue()));

Output


Key : 1 Value : Jan
Note
More examples, please read this Java 8 – Filter a Map examples

References

  1. java.util.Iterator JavaDoc
  2. java.util.Map JavaDoc
  3. Java 8 forEach examples
  4. Iterating over collections in Java 8

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
22 Comment threads
7 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
25 Comment authors
mkyongcalexandreSarada ChelluboyenaLuki R Danielmoxfun Recent comment authors
newest oldest most voted
Sarada Chelluboyena
Guest
Sarada Chelluboyena

Once we order treemap, can we loop from specific index?

Vic
Guest
Vic

one more 🙂

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

John
Guest
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

nikos lianeris
Guest
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

trackback
Compare Maps – Java | Tsetso's Stuff

[…] over Map Interface these 2 links were very useful for me:  Official Java Tutorial website and Mkyong’s website. Like this:LikeBe the first to like this […]

Sekhar
Guest
Sekhar

Suppose i have data like

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

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.

Nate
Guest
Nate

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

merve
Guest
merve

thanks, chic solutions

Alexander Podkutin
Guest
Alexander Podkutin

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

mintu
Guest
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

kiran
Guest
kiran

Thanks for Providing…

trackback
replacing few keywords with corresponding operators

[…] this out. He has some good examples. How to loop a Map in Java Writing code is your job, helping you fix and understand it is mine. Reply With […]

mukesh
Guest
mukesh

Thank you very mutch…

Jason.H
Guest
Jason.H

tks ~ bro , u’ve made lots of nice tutorials

Said Tahsin Dane
Guest
Said Tahsin Dane

The reason of using the entrySet iteration is for performance and not to use map.get(key). So the 3rd example is bad.

ashwa
Guest
ashwa

“url=http://www.krak.dk/53504900/s%C3%B8g.cs;
datasource=KRAK_YELLOW_DATA;
matchstring=hit-list;
url=http://www.krak.dk/53504900/s%C3%B8g.cs;
datasource=KRAK_YELLOW_DATA;
matchstring=hit-list”

i’ve string like above , save key value pair, i tryed but its overwriting, saved only one url,datasource,matchstring
can u please help me here

moxfun
Guest
moxfun

Hello, how to reverse order that? Thank you

Luki R Daniel
Guest
Luki R Daniel

your explanations are superb! thanks 😀

calexandre
Guest
calexandre

Simple explanation, thanks man!

Chinese dragon
Guest
Chinese dragon

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

trackback
How to read and parse CSV file in Java

[…] Loop a map in Java […]

mohd5912
Guest
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);
}
}