How to iterate through a Map (HashMap,TreeMap,Hashtable …)


   public static void main(String[] args) {

     Map map = new TreeMap();

        //TreeMap will use its keys’ natural ordering.
        //This class is an implementing class for SortedMap interface
        //Map (Interface)-> SortedMap(Interface) -> TreeMap (Class)

        map.put(“key1”, “value1”);
        map.put(“key2”, “value2”);
        map.put(“key3”, “value3”);
        map.put(“key4”, “value4”);
        map.put(“key5”, “value5”);
        map.put(“key6”, “value6”);
        map.put(“key7”, “value7”);

        for (Iterator it = map.keySet().iterator(); it.hasNext();) {
            Object key = it.next();
            System.out.println(“key –> ” + key +
                               ” value –> ” + map.get(key));
        }

       //OR use this syntax

        System.out.println(“Without using an iterator”);
        for (Object key : map.keySet()) {

            System.out.println(“key –> ” + key +
                               ” value –> ” + map.get(key));

    }
    }

Sample output;

run:
key –> key1 value –> value1
key –> key2 value –> value2
key –> key3 value –> value3
key –> key4 value –> value4
key –> key5 value –> value5
key –> key6 value –> value6
key –> key7 value –> value7
Without using an iterator
key –> key1 value –> value1
key –> key2 value –> value2
key –> key3 value –> value3
key –> key4 value –> value4
key –> key5 value –> value5
key –> key6 value –> value6
key –> key7 value –> value7
BUILD SUCCESSFUL (total time: 0 seconds)

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s