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, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

Leave a Reply

avatar
newest oldest most voted
Sarada Chelluboyena
Guest
Sarada Chelluboyena

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

calexandre
Guest
calexandre

Simple explanation, thanks man!

Luki R Daniel
Guest
Luki R Daniel

your explanations are superb! thanks :D

moxfun
Guest
moxfun

Hello, how to reverse order that? Thank you

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

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.

mkyong
Guest
mkyong

Thanks for your inputs.

Jason.H
Guest
Jason.H

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

mukesh
Guest
mukesh

Thank you very mutch…

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 […]

kiran
Guest
kiran

Thanks for Providing…

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

Alexander Podkutin
Guest
Alexander Podkutin

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

merve
Guest
merve

thanks, chic solutions

Nate
Guest
Nate

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

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.

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 […]

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

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

Som3
Guest
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
Guest
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
Guest
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
Guest
Vic

one more :)

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

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

Amarendra Kishore
Guest
Amarendra Kishore
It is too late for a reply, hope it will help somebody to understand :) Map entry; List<Map> data = new ArrayList<Map>(); String[] arrayAuthors = {“Author1”, “Author2”, “Author3”, “Author4”}; String[] arrayBooks = {“Book1”, “Book2”, “Book3”, “Book4”}; for (int i = 0; i < arrayAuthors.length; i++) { for (int i2 = 0; i2 < arrayBooks.length; i2++) { // Author/Book entry into map and add map to list entry = new HashMap(); entry.put(“Author”, arrayAuthors[i]); entry.put(“Title”, arrayBooks[i2]); data.add(entry); } } for(Map map:data){ for(Map.Entry dataentry: map.entrySet()){ System.out.println(dataentry.getKey() + “:” + dataentry.getValue()); } }
Suresh
Guest
Suresh

Map m=new LinkedHashMap();

String[] aa={“a”,”b”};

String[] bb={“b”,”b”};

for(int i=0;i<aa.length;i++)

{

for(int j=0;j<bb.length; j++)

{

m.put(aa[i], bb[j]);

}

}

System.out.println(m);

}

}

trackback
How to read and parse CSV file in Java

[…] Loop a map in Java […]

Chinese dragon
Guest
Chinese dragon

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