Map

The map enables us to store data in key-value pairs (keys should be immutable). A map in java cannot contain duplicate keys; each key can map to at most one value. The Map interface consists of three collection views, a set of keys, a collection of values, or a set of key-value mappings.
Eg –
Map< String,Integer> map = new HashMap< String,Integer>();
map.put(“a”, new Integer(100));

Types of Map –

  • HashMap –
    • It is the implementation of Map.
    • It doesn’t maintain any order.
    • It allows null keys and values.
    • Eg –
      • HashMap cities= new HashMap();
      • cities.put(“England”, “London”);
  • HashTable –
    • Hashtable implements the Map interface.
    • It is the same as HashMap but is synchronized.
    • Similar to HashMap, Hashtable stores key/value pairs in a hash table.
    • The key in hashtable is then hashed, which results in a hash code. This code is then used as the index at which the value is stored within the table.
    • Eg –
      • Hashtable table= new Hashtable();
      • table.put(“One”, new Double(3434.34));
  • LinkedHashMap –
    • LinkedHashMap is the implementation of Map.
    • It inherits the HashMap class.
    • It maintains insertion order.
    • It allows null keys and values.
    • Eg –
      • LinkedHashMap lhm = new LinkedHashMap();
      • lhm.put(“one”, “two”);
  • TreeMap –
    • TreeMap is the implementation of Map and SortedMap.
    • It maintains ascending order.
    • It doesn’t allow null keys and values.
    • E.g. –
      • TreeMap treemap = new TreeMap();
      • treemap.put(10, “One”);