Map#

(Map don't allow duplicate key)

Types of Map:

  • HashMap - unordered
  • LinkedHashMap - ordered
  • TreeMap (Sorted Map) - sorted by key

Instantiate#

Map<datatype, datatype> map = new HashMap <datatype, datatype> ();

Methods (map)#

  • put() - to insert/ update key,value pair in map

    map.put(key,value);
    //To add entire map to another
    map.putAll(Map map);
  • get() - to fetch the value of a key from map

    dataype value = map.get(key);
  • remove() - to remove the pair from the map

    map.remove(key);
  • size() - returns number of key/value pairs available in the map.

    int n = map.size();
  • containsKey() - returns true if key is present in the map

    boolean map.containsKey(key);
  • containsValue() - returns true if value is present in the map

    boolean map.containsValue(value);
  • keySet() - returns set view of map of all keys

    Set set = map.keySet();
  • values() - It returns a Collection view of the values contained in this map.

    List l = map.values();
  • entrySet() - method returns a complete set of keys and values present in the Map.

    Set<Map.Entry<datatype, datatpe>> set = map.entrySet();
  • Traversing Map

    // Traversing through the Map
    for (Map.Entry<datatype, datatype> me : map.entrySet()) {
    System.out.print(me.getKey() + ":");
    System.out.println(me.getValue());
    }