Class 10
Class 10
Maps are perfect to use for key-value association mapping such as dictionaries. The
maps are used to perform lookups by keys or when someone wants to retrieve and
update elements by keys. Some common scenarios are as follows:
A Map cannot contain duplicate keys and each key can map to at most one value. Some
implementations allow null key and null values like the HashMap and LinkedHashMap,
but some do not like the TreeMap.
There are two interfaces for implementing Map in Java. They are Map and SortedMap,
and three classes: HashMap, TreeMap, and LinkedHashMap.
The Map put() method associates the specified value with the specified key in the
map. The map put() method is used to insert new key-value pairs inside a map in
Java.
The map.remove() method is used to remove the mapping for a key from this map if it
is present in the map.
The java.util.Map.clear() method in Java is used to clear and remove all of the
elements or mappings from a specified Map collection.
The java.util.Map.entrySet() method in Java is used to create a set out of the same
elements contained in the map. It basically returns a set view of the map or we can
create a new set and store the map elements into them.
The java.util.Map.equals() method in Java is used to check for equality between two
maps. It verifies whether the elements of one map passed as a parameter is equal to
the elements of this map or not.
The get() method of Map interface in Java is used to retrieve or fetch the value
mapped by a particular key mentioned in the parameter. It returns NULL when the map
contains no such mapping for the key. So, let us check how to get value from the
map in Java.
This method is used to generate a hashCode for the given map containing key and
values.
This method is used to check if a map is having any entry for key and value pairs.
If no mapping exists, then this returns true.
This method is used to return a Set view of the keys contained in this map. The set
is backed by the map, so changes to the map are reflected in the set, and vice-
versa.
This method is used to copy all of the mappings from the specified map to this map.
HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.