My Hindi Forum

Go Back   My Hindi Forum > Miscellaneous > Tech Talks
Home Rules Facebook Register FAQ Community

Reply
 
Thread Tools Display Modes
Old 20-01-2010, 10:33 AM   #1
javaguru
Member
 
javaguru's Avatar
 
Join Date: Dec 2009
Posts: 50
Rep Power: 15
javaguru is on a distinguished road
Default How to iterate over Map?

Maps do not provide an iterator() method as do Lists and Sets. A Set of either keys (keySet()) or key-value Map.Entry elements (entrySet()) can be obtained from the Map, and one can iterate over that.

The order of the elements obtained from a Map depends on the type of Map they came from.

TreeMap
The elements are ordered by key.
HashMap
The elements will be in an unpredictable, "chaotic", order.
LinkedHashMap
The elements will be ordered by entry order or last reference order, depending on the type of LinkedHashMap.

Example - Iterating over the "entry set"

This example utility method prints the key-value pairs in a map.

Code:
// utility method dumpMap
public static void dumpMap(Map mp) {
    Iterator it = mp.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry pairs = (Map.Entry)it.next();
        System.out.println(pairs.getKey() + " = " + pairs.getValue());
    }
}
javaguru is offline   Reply With Quote
Reply

Bookmarks

Tags
java, map


Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off



All times are GMT +5. The time now is 04:35 PM.


Powered by: vBulletin
Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
MyHindiForum.com is not responsible for the views and opinion of the posters. The posters and only posters shall be liable for any copyright infringement.