Monday, January 7, 2013

Java - Various ways to iterate a Map (Hashtable, HashMap, TreeMap, LinkedHashMap)

A Map is collection that maps keys to values. A map cannot contain duplicate keys, each key can map to at most one value. Map comes with 4 different version - Hashtable, HashMap, TreeMap, LinkedHashMap.

Hashtable - Key methods of Hashtable are synchronized. Hashtable doesn't allow a null key or null values.

HashMap - HashMap allows one null key and multiple null values in a collection.

TreeMap - TreeMap is a sorted Map.

LinkedHashMap - LinkedHashMap maintains insertion order.

Below are the methods in which you can iterate a Map.

1. Iterator - Using Iterator you can iterate HashMap, TreeMap, LinkedHashMap.

2. Enumeration - Using Enumeration you can iterate Hashtable.

3. Also you can iterate values of a Map using values() and elements() method.

Please see the below code.

No comments:

Post a Comment