Skip to content
Avinandan Bose edited this page Dec 23, 2022 · 8 revisions

JavaUtilMap

Here is all about Map of Java

1. AbstractMap

  • 1. Every class of Java is inherited from java.lang.Object

  • 2. The AbstractMap class is the base class of the map classes in Java.

sequenceDiagram
    
  
  java.lang.Object->>java.util.AbstractMap: 

Loading
  • 3. The AbstractMap class is a part of the Java Collection Framework.

  • 4. It directly implements the Map interface to provide a structure to it.

  • 5. AbstractMap is an abstract class, hence we cannot create AbstractMap's Object but the concrete classes that inherit from AbstractMap can be used to create objects .


  • Interface Hash Table Resizable Array Balanced Tree Linked List
    Map HashMap TreeMap
    SortedMap TreeMap
    NavigableMap TreeMap
    Map.Entry(Inner Class of Map)

    public abstract class AbstractMap<K,V> extends Object, implements Map<K,V>
    

    2. Map Interface

    • 1. A map stores data in Key/Value pairs much like an array.

    • 2. Every Key/Value pairs stored in indexes .

    • 3. Every Key/Value pairs are stored as Objects in Java.

    • 4. Typically , keys are Strings.

    • 5. Given a Key and a Value, we can store the value in a Map object.

    • 6. After the value is stored , we can retrieve it by using its Key.

    • 7. Map is generic and is declared :

    • interface Map<K,V>
      

      Where, K specifies the type of keys and V specifies the type of values.

    • 8. Map do not implement the Iterable interface. Futhermore Iterator also cannot be obtained by a map.

    That is :
    
    import java.util.Iterator;
    import  java.lang.Iterable;
    
    Iterable<Map<Key, Value>> itr = map; → Cannot be Obtained
    
    Or
    
    Iterator<Map<Key, Value>> iterator = map.iterator(); → Cannot be Obtained
    
    Interface Description
    Map Maps unique keys to values.
    Map.Entry Describes an element (a key/value) in a map. This is an inner class of Map.
    NavigableMap It extends SortedMap to handle the retrieval of entries based on closest-match searches.
    SortedMap It extends Map to keep the keys in ascending order.

    3. HashMap

      1. HashMap extends Abstract Map abstract class.

      2. As Abstract Map implements Map interface and extends java.lang.Object class , HashMap inherits all of their functions.

    • 3. And most imported thing : "The HashMap provides us an unsorted, unordered Map ".

    • 4. HashMap has implementation based on a Hash table.

    • 5. Duplicate keys are not allowed i.e. Keys are unique .

    • 6. Whereas, Duplicate values can be present / allowed .

      
     graph TD;
        Object-->|extends| AbstractMap;
        Map-->|implements| AbstractMap;
        AbstractMap-->|extends| HashMap;
    
    
    Loading

    Constructors of HashMap

    :ThresHold of HashMap, Capacity and LoadFactor:
    --------------------------------------------------
    
    ThresHold of HashMap : 
    The threshold of a HashMap is approximately the product of current capacity and load factor
    
    LoadFactor : 
    The load factor is the measure that decides when to increase the capacity of the Map.
    
    Capacity of HashMap: 
    Capacity is the number of buckets in the HashMap. 
    
    Default Capacity of HashMap: 16
    That is empty HashMap created with capacity 16.
    
    Default LoadFactor of HashMap: 0.75
    That is empty HashMap created with Load Factor 0.75.
    
    Default Threshold of HashMap: is 16 * 0.75 = 12.
    That is empty HashMap created with threshold 12.
    

    HashMapStructure-660x545

    Extras:

    Index: 
    It is the integer value .
    It is obtained after performing → 
    Bitwise AND operation on the Value of Hash of the Key and Array Size Minus One.
    
    i.e., :| Index = hashcode(key) & (ArraySize – 1) |:
    
    
    Bucket: It is a LinkedList structure of nodes.
    
    
    Node: It is the elementary unit of a HashMap. 
    It contains the key-value pair and a link to the next node.
    
    Next: Link to the next node.
    
    It is represented as:  Node<K,V> next.
    
    Where K represents Key and V represents Value.
    
    Rehashing: It is the process of doubling the capacity of the HashMap ,
    after it reaches its Threshold. In java, HashMap continues to 
    rehash(by default) in the following sequence – 2^4, 2^5, 2^6, 2^7, …. so on. 
    
    
    
    

    node_hash_map

    Methods of HashMap

    It removes all the mappings of this map.
    The map will be empty after this call returns.
    
    Returns a shallow copy of the HashMap instance provided for cloning
    but the keys and values themselves are not cloned.
    
    Returns true if this map contains a mapping for the specified key.
    
    Returns true if this map maps one or more keys to the specified value.
    
    Performs the given action for each entry in this map 
    until all entries have been processed or the action throws an exception.
    
    Syntax: get(key: Key)
    
    Returns the value to which the specified key is mapped, 
    or null if this map contains no mapping for the key.
    
    Syntax: getOrDefault(key: Key , defaultValue:Value)
    
    Returns the value to which the specified key is mapped, 
    or defaultValue if this map contains no mapping for the key.
    
    i.e.,getOrDefault(key:"One" , defaultValue:1)
    then it will return the value for the key : "One"
    Or, it will return the value for the value : 1
    
    Most priority given or first search is Key for Value .
    If not found , then it searches for defaultValue for value.
    
    That is if "One" is not found then it searches for 1.
    Returns true if this map contains no key-value mappings.
    Returns 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.
    
    Note:
    As Set<K> keySet()→ Is a Function that returns Set,
    Hence, it call all those functions that Set contains,
    Such as:
    →forEach
    →toArray()
    →remove()
    →removeIf()
    →retainAll()
    →removeAll()
    →Stream()
    →ParallelStream()
    →spliterator()
    →iterator()
    →contains()
    →containsAll()
    ...etc.
    
    It does not support the add or addAll operations.
    Associates the specified value with the specified key in this map. 
    If the map previously contained a mapping for the key, 
    the old value is replaced.
    Copies all of the mappings from the specified map to this map. 
    These mappings will replace any mappings that this map had ,
    for any of the keys currently in the specified map.
    Removes the mapping for the specified key from this map if present.
    Removes the entry for the specified key only if it is currently mapped to the specified value.
    Replaces the entry for the specified key only if currently mapped to the specified value.
    It replaces old value with new value.
    Replaces each entry's value with the result of invoking the given function,
    on that entry until all entries have been processed or 
    the function throws an exception.
    Returns the number of key-value mappings in this map.
    Returns a Collection view of the values contained in this map.
    
    Note:
    Iterator.remove
    Iterator.hasNext()
    Iterator.next()
    Collection.remove, 
    Collection.removeAll, 
    Collection.removeIf,
    Collection.retainAll and 
    Collection.clear 
    
    like selected operations is performed,
    as it returns a Collection.
    
    Except:
    
    It does not support the add or addAll operations.
    If the specified key is not already associated with a value ,
    then associates it with the given value .
    
    If the specified key is not already associated with a value,
    and now the new value mapped with the new key is NULL , 
    then it will return null. 
    Attempts to compute a mapping for the specified key and 
    its current mapped value (or null if there is no current mapping).
    If the specified key is not already associated with a value 
    (or is mapped to null), attempts to compute its value,
    using the given mapping function and
    enters it into this map unless null.
    
    If the mapping function returns null, no mapping is recorded.
    If the value for the specified key is present and non-null, 
    attempts to compute a new mapping given the key 
    and its current mapped value.
    
    If the remapping function returns null, the mapping is removed.
    Returns a Set view of the mappings contained in this map. 
    The set is backed by the map, 
    so changes to the map are reflected in the set, 
    and vice-versa. 
    
    
    As entrySet()→ Is a Function that returns Set,
    Hence, it call all those functions that Set contains,
    Such as:
    →forEach
    →toArray()
    →remove()
    →removeIf()
    →retainAll()
    →removeAll()
    →Stream()
    →ParallelStream()
    →spliterator()
    →iterator()
    →contains()
    →containsAll()
    ...etc.
    
    It does not support the add or addAll operations.
    If the specified key is not already associated with a value
    or is associated with null, associates it with the given non-null value. 
    Otherwise, replaces the associated value with the results of the given remapping function, 
    or removes if the result is null. 
    
    This method may be of use when combining multiple mapped values for a key.
    Replaces the entry for the specified key only if it is currently mapped to some value.
    Methods Does This
    1. Clear It removes all of the mappings from the map.
    2.Clone It gets a copy of this HashMap instance
    3.containsKey Returns true if this map contains a mapping for the specified key.
    4.containsValue Returns true if this map maps one or more keys to the specified value.
    5.forEach Performs the given action for each entry in this map until all entries have been processed or the action throws an exception.
    6.get(key: Key) Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.
    7.getOrDefault(key: Key , defaultValue:Value) Returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key.
    8.isEmpty Returns true if this map contains no key-value mappings.
    9.KeySet Returns 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.If the map is modified while an iteration over the set is in progress (except through the iterator's own remove operation), the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll, and clear operations. It does not support the add or addAll operations.
    10.Put Associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced.
    11.PutAll Copies all of the mappings from the specified map to this map. These mappings will replace any mappings that this map had , for any of the keys currently in the specified map.
    12.Remove(key: Key) Removes the mapping for the specified key from this map if present.
    13.Remove(key: Key, value:Value) Removes the entry for the specified key only if it is currently mapped to the specified value.
    14.Replace(key: Key, oldValue:Value, newValue:Value) Replaces the entry for the specified key only if currently mapped to the specified value. It replaces old value with new value.
    15.ReplaceAll(BiFunction function) Replaces each entry's value with the result of invoking the given function, on that entry until all entries have been processed or the function throws an exception.
    16.Size() Returns the number of key-value mappings in this map.
    17.values() Returns a Collection view of the values contained in this map.
    18.putIfAbsent() If the specified key is not already associated with a value , then associates it with the given value .
    19.compute(key:Key,BiFunction function) Attempts to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping).
    20.computeIfAbsent(key:Key, MappingFunction function) If the specified key is not already associated with a value (or is mapped to null), attempts to compute its value, using the given mapping function and enters it into this map unless null.

    If the mapping function returns null, no mapping is recorded.

    21.computeIfPresent(key:Key, BiFunction function) If the value for the specified key is present and non-null, attempts to compute a new mapping given the key and its current mapped value.

    If the remapping function returns null, the mapping is removed.

    22.entrySet() Returns a Set view of the mappings contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in progress (except through the iterator's own remove operation, or through the setValue operation on a map entry returned by the iterator) the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll and clear operations.It does not support the add or addAll operations.
    23.merge(key:Key, value:Value, BiFunction remappingFunction) If the specified key is not already associated with a value or is associated with null, associates it with the given non-null value. Otherwise, replaces the associated value with the results of the given remapping function, or removes if the result is null.

    This method may be of use when combining multiple mapped values for a key.

    24.Replace(key:Key, value:Value) Replaces the entry for the specified key only if it is currently mapped to some value.

    Methods inherited from class java.util.AbstractMap

    Compares the specified object with this map for equality. 
    Returns true if the given object is also a map and the two maps represent the same mappings. 
    
    More formally, two maps m1 and m2 represent the same mappings,
    if m1.entrySet().equals(m2.entrySet()).
    Returns a string representation of this map. 
    Returns the hash code value for this map. 
    Methods Does This
    1.equals() Compares the specified object with this map for equality. Returns true if the given object is also a map and the two maps represent the same mappings.
    toString() Returns a string representation of this map.
    hashCode() Returns the hash code value for this map.

    Note: Map interface →java.util.Map contains: equals(), forEach(), getOrDefault(), hashCode(), putIfAbsent(), remove(), replace(), replaceAll() functions inherited by HashMap() have same actions in program .

    Division of Abstract Map

     
     graph TD;
        Map-->|implements| AbstractMap;
        AbstractMap-->|extends| HashMap;
        AbstractMap-->|extends| IdentityHashMap;
        AbstractMap-->|extends| WeakHashMap;
        AbstractMap-->|extends| TreeMap;
        AbstractMap-->|extends| EnumMap;
        AbstractMap-->|extends| ConcurrentHashMap;
        AbstractMap-->|extends| ConcurrentSkipListMap;
        HashMap-->|extends| LinkedHashMap; 
    
    Loading

    Linked Hash Map

    sequenceDiagram
        
      
      java.util.Map->>java.util.HashMap:implements 
      java.util.HashMap->>java.util.LinkedHashMap:extends
      
      
    
    Loading
  • 1. A LinkedHashMap is an extension of the HashMap class and it implements the Map interface.

  • public class LinkedHashMap<K,​V> extends HashMap<K,​V> implements Map<K,​V>
    

  • 2.The implementation of the LinkedHashMap is very similar to a doubly-linked list. Therefore, each node of the LinkedHashMap is represented as:

  • Screenshot (197)

    • Hash: All the input keys are converted into a hash which is a shorter form of the key so that the search and insertion are faster.

    • Key: Since this class extends HashMap, the data is stored in the form of a key-value pair. Therefore, this parameter is the key to the data.

    • Value: For every key, there is a value associated with it. This parameter stores the value of the keys. Due to generics, this value can be of any form.

    • Next: Since the LinkedHashMap stores the insertion order, this contains the address to the next node of the LinkedHashMap.

    • Previous: This parameter contains the address to the previous node of the LinkedHashMap.

  • 3.The implementation of LinkedHashMap is not synchronized.

  • 4.It contains only unique elements.

  • 5.It may have one null key and multiple null values.

  • 6.It is the same as HashMap with an additional feature that it maintains insertion order. For example, when we run the code with a HashMap, we get a different order of elements.

  • That is, It first take elements according to their hash,

    Then if any insertion occurs it inserts them as (doubly)linked list.

    Constructors of LinkedHashMap

    It is used to construct a default LinkedHashMap.
    
    Constructs an empty insertion-ordered LinkedHashMap instance ,
    with the default initial capacity (16) and load factor (0.75).
        
  • It is used to initialize a LinkedHashMap with the given capacity.
    
    Constructs an empty insertion-ordered LinkedHashMap instance ,
    with the specified initial capacity and a default load factor (0.75).
        
  • It is used to initialize both the capacity and the load factor.
    
    Constructs an empty insertion-ordered LinkedHashMap instance,
    with the specified initial capacity and load factor.
        
  • It is used to initialize both the capacity and the load factor with specified ordering mode.
    
    Constructs an empty LinkedHashMap instance ,
    with the specified initial capacity, load factor and ordering mode.
        
  • It is used to initialize the LinkedHashMap with the elements from the given Map class m.
    
    Constructs an insertion-ordered LinkedHashMap instance ,
    with the same mappings as the specified map. 
    The LinkedHashMap instance is created with a default load factor (0.75) 
    and an initial capacity sufficient to hold the mappings in the specified map.
        
    Constructor Description
    LinkedHashMap() It is used to construct a default LinkedHashMap. Constructs an empty insertion-ordered LinkedHashMap instance , with the default initial capacity (16) and load factor (0.75).
    LinkedHashMap(int capacity) It is used to initialize a LinkedHashMap with the given capacity.Constructs an empty insertion-ordered LinkedHashMap instance , with the specified initial capacity and a default load factor (0.75).
    LinkedHashMap(int capacity, float loadFactor) It is used to initialize both the capacity and the load factor.Constructs an empty insertion-ordered LinkedHashMap instance, with the specified initial capacity and load factor.
    LinkedHashMap(int capacity, float loadFactor, boolean accessOrder) It is used to initialize both the capacity and the load factor with specified ordering mode.Constructs an empty LinkedHashMap instance , with the specified initial capacity, load factor and ordering mode.
    LinkedHashMap(Map extends K,? extends V> m) It is used to initialize the LinkedHashMap with the elements from the given Map class m.Constructs an insertion-ordered LinkedHashMap instance , with the same mappings as the specified map. The LinkedHashMap instance is created with a default load factor (0.75) and an initial capacity sufficient to hold the mappings in the specified map.

    Methods of LinkedHashMap

    • New Method :

      Methods Does This
      removeEldestEntry() It is used keep a track of whether the map removes any eldest entry from the map. So each time a new element is added to the LinkedHashMap, the eldest entry is removed from the map. This method is generally invoked after the addition of the elements into the map by the use of put() and putall() method.
    It is used keep a track of whether the map removes any eldest entry from the map. 
    So each time a new element is added to the LinkedHashMap, the eldest entry is removed from the map. 
    This method is generally invoked after the addition of the elements into the map,
    by the use of put() and putall() method.
    
    Eg:
    
    If Map = {a=1, b=2, c=3, d=4, e=5, f=6, g=7, h=8, i=9, j=10}
    
    Then, removeEldestEntry :
    Size < 1 or Size ==0  → {a=1, b=2, c=3, d=4, e=5, f=6, g=7, h=8, i=9, j=10}
    Size > 1 = {j=10}
    Size > 2 = {i=9, j=10}
    Size > 3 = {h=8, i=9, j=10}
    ..... etc.

    Synchronization of LinkedHashMap

    • 1.The implementation of LinkedHashMap is not synchronized.

    • 2.If multiple threads access a linked hash map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally.This is typically accomplished by synchronizing on some object that naturally encapsulates the map.

    • 3. If no such object exists, the map should be “wrapped” using the Collections.synchronizedMap method . This is best done at creation time, to prevent accidental unsynchronized access to the map.

    Identity Hash Map

    sequenceDiagram
        
      
      java.util.Map->>java.util.AbstractMap:implements 
      java.util.AbstractMap->>java.util.IdentityHashMap:extends
      
      
    
    Loading
  • 1. A IdentityHashMap is an extension of the AbstractMap class and it implements the Map interface.

  • 2. It is not synchronized and must be synchronized externally.

  • 3. It uses reference equality rather than using the equals() method. It uses the == operator.

  • 4. Iterators are fail-fast, throw ConcurrentModificationException in an attempt to modify while iterating.ConcurrentModificationException exception may be thrown by methods that have detected concurrent modification of an object when such modification is not permissible.

  • public class IdentityHashMap<K,​V> extends AbstractMap<K,​V> implements Map<K,​V>
    

    Constructors of IdentityHashMap

    Constructs a new, empty identity hash map with a default expected maximum size (21).
        
  • It creates a new and empty identity hash map with the given specified expected maximum size.
    
    Constructs a new, empty map with the specified expected maximum size. 
    Putting more than the expected number of key-value mappings into the map ,
    may cause the internal data structure to grow, which may be somewhat time-consuming.
        
  • It creates a new identity hash map with the key-value pairs given in the specified map.
    
    Constructs a new identity hash map containing the keys-value mappings in the specified map.
        
    Constructor Does This
    IdentityHashMap() Constructs a new, empty identity hash map with a default expected maximum size (21).
    IdentityHashMap(int ExpectedMaxSize) It creates a new and empty identity hash map with the given specified expected maximum size. Constructs a new, empty map with the specified expected maximum size. Putting more than the expected number of key-value mappings into the map , may cause the internal data structure to grow, which may be somewhat time-consuming.
    IdentityHashMap(Map m) It creates a new identity hash map with the key-value pairs given in the specified map.

    Constructs a new identity hash map containing the keys-value mappings in the specified map.

    Methods of IdentityHashMap

    For Hash Map:
    
    map.put("a", 1);
    
    a is a String constant and 1 is Integer constant.
    
    map.put(new String("a"), 2);
    
    Here a is an object of String and 2 is an Integer constant.
    
    But in HashMap it check key as :
    
    map.put("a", 1).equals(map.put(new String("a"), 1));
    
    i.e., it treats constant and object is equal as Keys are same i.e. "a".
    
    i.e. "a".equals("a")
    
    Which returns true , where as:
    
    For Identity Hash Map:
    
    map1.put("a", 1).equals(map1.put(new String("a"), 1))
    
    Here it treats constant and object are different i.e.
    
    "a" not equal to {new String("a")}
    
    i.e. it uses:
    
    "a" == {new String("a")} which is false
    
    Hence it creates : {a=1,a=1} map
    
    
    Now in Identity Hash Map: 
    
     map1.put("a", 2); will update,
     1st Key which have String constant ,
     
     i.e. : {a=2,a=1}
     
    map1.put(new String("a"), 2); will update,
    2nd Key which have String object ,
    
     i.e. : {a=2,a=2}
     
     While for HashMap:
     map.put("a", 1);
     = {a=1}
     map.put(new String("a"),2}
     =  {a=2}
     map.put("a",3}
     =  {a=3}
     
     .... etc
     
     This is the differnce between Hash Map and Identity Map.

    Synchronized IdentityHashMap

      When more than one threads access the identity hash map concurrently, and at least one of the threads structurally modifies the map, it is necessary to synchronize that map externally. (Structural modification of map is to add or delete one or more key value mappings. If we just change the value associated with a key that an instance contains already is not structural modification.)

      It can be achieved by synchronizing on any object that encapsulate the map. If such object doesn't exist, map should be wrapped with the help of Collections.synchronizedMap() method. The correct time to do this is at the time of creation, in order to prevent unsynchronized access to map.

    Clone this wiki locally