Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/avinandanbose/java-collections-map

Here is all about Map of Java
https://github.com/avinandanbose/java-collections-map

java java10 java4 java5 java6 java7 java8 java9 javacollection javacollections javamap javamapcollections map mapping mappings maps

Last synced: about 1 month ago
JSON representation

Here is all about Map of Java

Awesome Lists containing this project

README

        

# Java Collections Map
Here is all about Map of Java

1. AbstractMap[Abstract Class]



  • 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.


  • ```mermaid

    sequenceDiagram


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

    ```

  • 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)

    ```Syntax

    public abstract class AbstractMap extends Object, implements Map

    ```


    Methods of Abstract Map(Abstract Class)

      Methods of Abstract Map(Abstract Class)
      Does This

      1. clear()
      Removes all of the mappings from this map .

      2.clone()
      Returns a shallow copy of this map.

      3. containsKey(Object key)
      Returns true if this map contains a mapping for the specified key.

      4. containsValue(Object value)
      Returns true if this map maps one or more keys to the specified value.

      5.entrySet()
      Returns a Set view of the mappings contained in this map.

      6. equals(Object o)
      Compares the specified object with this map for equality.

      7. get(Object key)
      Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

      8. hashCode()
      Returns the hash code value for this map.

      9. isEmpty()
      Returns true if this map contains no key-value mappings.

      10. keySet()
      Returns a Set view of the keys contained in this map.

      11. put(K key, V value)
      Associates the specified value with the specified key in this map .

      12. putAll(Map extends K,? extends V> m)
      Copies all of the mappings from the specified map to this map .

      13. remove(Object key)
      Removes the mapping for a key from this map if it is present.

      14.size()
      Returns the number of key-value mappings in this map.

      15.toString()
      Returns a string representation of this map.

      16.values()
      Returns a Collection view of the values contained in this map.

      Note: These methods are discussed below .


A. 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 :

  • ```Syntax

    interface Map

    ```

    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.

    • ```Syntax

      That is :

      import java.util.Iterator;
      import java.lang.Iterable;

      Iterable> itr = map; → Cannot be Obtained

      Or

      Iterator> 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.


Methods of Map Interface


    Methods of Map Interface
    Does This

    1. clear()
    Removes all of the mappings from this map

    2. compute(K key, BiFunction super K,? super V,? extends V> remappingFunction)
    Attempts to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping).

    3. computeIfAbsent(K key, Function super K,? extends V> mappingFunction)
    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.

    4. computeIfPresent(K key, BiFunction super K,? super V,? extends V> remappingFunction)
    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.

    5. containsKey(Object key)
    Returns true if this map contains a mapping for the specified key.

    6. containsValue(Object value)
    Returns true if this map maps one or more keys to the specified value.

    7. entrySet()
    Returns a Set view of the mappings(All Entries) contained in this map.

    8. equals(Object o)
    Compares the specified object with this map for equality.

    9. forEach(BiConsumer super K,? super V> action)
    Performs the given action for each entry in this map until all entries have been processed or the action throws an exception.

    10. get(Object key)
    Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

    11. getOrDefault(Object key, V defaultValue)
    Returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key.

    12. hashCode()
    Returns the hash code value for this map.

    13. isEmpty()
    Returns true if this map contains no key-value mappings.

    14.keySet()
    Returns a Set view of the keys contained in this map.

    15.merge(K key, V value, BiFunction super V,? super V,? extends V> 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.

    16.put(K key, V value)
    Associates the specified value with the specified key in this map.

    17.putAll(Map extends K,? extends V> m)
    Copies all of the mappings from the specified map to this map.

    18.putIfAbsent(K key, V value)
    If the specified key is not already associated with a value (or is mapped to null) associates it with the given value and returns null, else returns the current value.

    19.remove(Object key)
    Removes the mapping for a key from this map if it is present.

    20.remove(Object key, Object value)
    Removes the entry for the specified key only if it is currently mapped to the specified value.

    21.replace(K key, V value)
    Replaces the entry for the specified key only if it is currently mapped to some value.

    22.replace(K key, V oldValue, V newValue)
    Replaces the entry for the specified key only if currently mapped to the specified value.

    23.replaceAll(BiFunction super K,? super V,? extends V> 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.

    24.size()
    Returns the number of key-value mappings in this map.

    25.values()
    Returns a Collection view of the values contained in this map.

    Note: These methods are discussed below .



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 .


  • ```mermaid

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

    ```

    Constructors of HashMap

    ```Syntax

    :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](https://user-images.githubusercontent.com/38869235/208160027-ee575296-d999-4a80-898a-b6e69aeccefc.jpg)

    Extras:

    ```Syntax

    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 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](https://user-images.githubusercontent.com/38869235/208721084-f55b0f8d-15b0-4e81-a90a-919f77b66851.png)

    Methods of HashMap


      1.Clear

      ```Syntax

      It removes all the mappings of this map.
      The map will be empty after this call returns.

      ```

      2.Clone

      ```Syntax
      Returns a shallow copy of the HashMap instance provided for cloning
      but the keys and values themselves are not cloned.

      ```

      3.containsKey

      ```Syntax
      Returns true if this map contains a mapping for the specified key.

      ```

      4.containsValue

      ```Syntax
      Returns true if this map maps one or more keys to the specified value.

      ```

      5.forEach

      ```Syntax
      Performs the given action for each entry in this map
      until all entries have been processed or the action throws an exception.

      ```

      6.get



      ```Syntax

      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.

      ```

      7.getOrDefault

      ```Syntax

      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.
      ```

      8.isEmpty

      ```Syntax

      Returns true if this map contains no key-value mappings.
      ```

      9.KeySet

      ```Syntax

      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 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.
      ```

      10.Put

      ```Syntax

      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

      ```Syntax

      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)

      ```Syntax
      Removes the mapping for the specified key from this map if present.
      ```

      13.Remove(key: Key, value:Value)

      ```Syntax
      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)

      ```Syntax
      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)

      ```Syntax
      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()

      ```Syntax
      Returns the number of key-value mappings in this map.
      ```

      17.values()

      ```Syntax
      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.
      ```

      18.putIfAbsent()

      ```Syntax
      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.
      ```

      19.compute(key:Key,BiFunction function)

      ```Syntax
      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)

      ```Syntax
      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)

      ```Syntax
      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()

      ```Syntax
      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.
      ```

      22.merge(key:Key, value:Value, BiFunction remappingFunction)

      ```Syntax
      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)

      ```Syntax
      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


      1.equals()

      ```Syntax
      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()).
      ```

      2.toString()

      ```Syntax
      Returns a string representation of this map.
      ```

      3.hashCode()

      ```Syntax
      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.

      2.toString()
      Returns a string representation of this map.

      3.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

    ```mermaid

    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;
    AbstractMap-->|extends| Object;
    ConcurrentHashMap-->|implements| ConcurrentMap;
    ConcurrentSkipListMap-->|implements| ConcurrentNavigableMap;
    HashMap-->|extends| LinkedHashMap;
    ConcurrentMap-->|extends| Map;
    Map-->|extends| SortedMap;
    SortedMap-->|extends| NavigableMap;
    TreeMap-->|implements| NavigableMap;
    ConcurrentNavigableMap-->|extends| ConcurrentMap;
    ConcurrentNavigableMap-->|extends| NavigableMap;
    HashTable-->|implements|Map
    ```



Linked Hash Map

    ```mermaid

    sequenceDiagram


    java.util.Map->>java.util.HashMap:implements
    java.util.HashMap->>java.util.LinkedHashMap:extends


    ```

  • 1. A LinkedHashMap is an extension of the HashMap class and it implements the Map interface.

  • ```Syntax

    public class LinkedHashMap extends HashMap implements Map

    ```

  • 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)](https://user-images.githubusercontent.com/38869235/208919283-fb2e1253-4e47-430b-a3a3-4a6522687238.png)



    • 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



    • 1.LinkedHashMap()

    • ```Syntax

      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).

      ```

    • 2.LinkedHashMap(int capacity)

    • ```Syntax

      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).

      ```

    • 3.LinkedHashMap(int capacity, float loadFactor)

    • ```Syntax

      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.

      ```

    • 4.LinkedHashMap(int capacity, float loadFactor, boolean accessOrder)

    • ```Syntax

      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.

      ```

    • 5.LinkedHashMap(Map extends K,? extends V> m)

    • ```Syntax

      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



    • 1. All HashMap and AbstractMap Functions in 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.

    • 2. removeEldestEntry()

    • ```Syntax

      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

    ```mermaid

    sequenceDiagram


    java.util.Map->>java.util.AbstractMap:implements
    java.util.AbstractMap->>java.util.IdentityHashMap:extends
    java.io.Serializable->>java.util.IdentityHashMap:implements
    java.lang.Cloneable->>java.util.IdentityHashMap:implements
    ```

  • 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.

  • ```Syntax

    public class IdentityHashMap extends AbstractMap implements Map
    ,Serializable, Cloneable

    ```



    Constructors of IdentityHashMap


    • 1.IdentityHashMap()

    • ```Syntax
      Constructs a new, empty identity hash map with a default expected maximum size (21).

      ```

    • 2.IdentityHashMap(int ExpectedMaxSize)

    • ```Syntax
      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.

      ```

    • 3.IdentityHashMap(Map m)

    • ```Syntax
      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



    • 1. All HashMap and AbstractMap Functions in IdentityHashMap


    • 2. Difference between HashMap and Identity HashMap.



      • Difference between HashMap and Identity HashMap

      • ```Syntax

        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.




Weak Hash Map

    ```mermaid

    sequenceDiagram


    java.util.Map->>java.util.AbstractMap:implements
    java.util.AbstractMap->>java.util.WeakHashMap:extends


    ```

    ```Syntax

    public class WeakHashMap extends AbstractMap implements Map

    ```

  • 1. WeakHashMap is an implementation of the Map interface, that stores only weak references to its keys.


  • 2. Storing only weak references allows a key-value pair to be garbage-collected when its key is no longer referenced outside of the WeakHashMap.


  • 3. WeakHashMap does not implement Cloneable interface, hence it doesnot have clone() functionality.

  • 4. If object is specified as key doesn’t contain any references- it is eligible for Garbage Collection even though it is associated with WeakHashMap. i.e. Garbage Collector dominates over WeakHashMap.

  • 5. In WeakHashmap, When a key is discarded then its entry is automatically removed from the map, in other words, garbage collected.


  • WeakReference Vs Strong Reference[on Reference to Hash Map and Weak Map]



      1.Strong Reference:

      ```Syntax

      public class example {
      public static void main(String[] args) {
      example obj = new example();
      obj = null;
      System.gc();
      }


      }

      ```

      Here "obj" object has strong reference to the instance of class "example" .


      Hence Not eligible for garbage collection until:

      ```Syntax

      obj = null

      ```

      i.e. The object is garbage collected only when the variable which was strongly referenced points to null.


      As 'obj' object is no longer referencing to the instance of class: "example".


      Best example:

      ```Syntax

      class ex{
      public void finalize(){
      System.out.println("Finalize method called");
      }
      }
      public class example {
      public static void main(String[] args) {
      ex obj = new ex();
      obj.finalize();
      obj = null;
      System.gc();//Garbage Collector
      obj.finalize();//will not call finalize method and throws Null Pointer Exception
      }


      }

      ```


      In HashMap, key objects have strong references.

    2.Weak Reference:



    • 1. This type of reference is used in WeakHashMap to reference the entry objects .


    • 2. If JVM detects an object with only weak references (i.e. no strong or soft references linked to any object), this object will be marked for garbage collection.


    • 3. To create such references java.lang.ref.WeakReference class is used.


    • 4. Weak Reference Objects are not the default type/class of Reference Object. They are explicitly specified while using them.

    • ```Syntax

      import java.lang.ref.WeakReference;

      class exceptions {
      void print() {
      System.out.println("Print method called");
      }
      }

      public class WeakRefexample {
      public static void main(String[] args) {

      // Strong Reference
      exceptions obj = new exceptions();
      obj.print();

      // Weak Reference has explicit type class[exceptions] of Reference Object[obj]
      WeakReference weak = new WeakReference<>(obj);

      obj = null;
      exceptions obj1 = weak.get();

      /**
      *
      * get() function : It returns this reference object's referent.
      * If this reference object has been cleared,
      * either by the program or by the garbage collector,
      * then this method returns null.
      *
      **/

      obj1.print(); // will call print method and will not throw any exceptions
      }

      }

      ```




    Constructors of WeakHashMap


    • 1.WeakHashMap()

    • ```Syntax

      It is used to construct a default constructor of WeakHashMap.

      This constructor constructs a new,
      empty WeakHashMap with the default initial capacity (16)
      and the default load factor (0.75).

      ```

    • 2.WeakHashMap(int initialCapacity)

    • ```Syntax

      This constructor constructs a new,
      empty WeakHashMap with the given
      initial capacity and
      the default load factor, which is 0.75.

      ```

    • 3.WeakHashMap(int initialCapacity, float loadFactor)

    • ```Syntax

      This constructor constructs a new, empty WeakHashMap
      with the given initial capacity and the given load factor.

      ```

    • 4.WeakHashMap(Map m)

    • ```Syntax

      This constructor constructs a new WeakHashMap ,
      with the same mappings as the specified Map.

      ```


      Constructor
      Does This


      WeakHashMap()
      It is used to construct a default constructor of WeakHashMap.This constructor constructs a new,
      empty WeakHashMap with the default initial capacity (16)
      and the default load factor (0.75).

      WeakHashMap(int initialCapacity)
      This constructor constructs a new,
      empty WeakHashMap with the given
      initial capacity and
      the default load factor, which is 0.75.

      WeakHashMap(int initialCapacity, float loadFactor)
      This constructor constructs a new, empty WeakHashMap
      with the given initial capacity and the given load factor.

      WeakHashMap(Map m)
      This constructor constructs a new WeakHashMap ,
      with the same mappings as the specified Map.



    Methods of WeakHashMap



    • 1.All Weak HashMap Methods


    • 2. Weak HashMap Vs Hash Map

    • ```Syntax
      Consider a Class:

      class demo{
      @Override
      public String toString() {
      return "demo";
      }
      public void finalize(){
      System.out.println("Finalize method called");
      }

      }

      Now:

      class weakhashmap2{
      public static void main(String[] args){
      WeakHashMap map = new WeakHashMap<>();
      demo d = new demo();
      map.put(d, 1);

      Now:

      : Object is assigned to null :

      d = null;

      : And , Grabage Collector is called :

      System.gc();

      : Which will empty the Map as it is a Weak Reference :
      : As, Weak Reference is cleared by gc :

      Next:
      We input Key as d and an integer 1 in the map:
      map.put(d, 1);
      we know d has already assigned to null hence the output: Map:{null=1}

      Now we create another object say :
      demo d2 = new demo();
      map.put(d2, 2);

      So output will be: Map:{null=1, demo=2}

      : Hence it signifies the WeakReference of Key, Value pair in Weak HashMap. :

      : But in Hash Map :

      HashMap m = new HashMap<>();
      demo d1 = new demo();
      m.put(d1, 1);

      :Output: Map = {demo=1}

      d1 = null;//Object is referenced to null.
      System.gc();//garbage collector is called.

      :And again if map is called:
      :It will put Object → d1 and Integer→ 1 :
      :As HashMap is strongly referenced to Object → d1 and Integer→ 1:

      System.out.println( m);

      :Output → {demo=1}:

      Now we create another object say :
      demo d3 = new demo();
      m.put(d3, 2);
      System.out.println( m);

      :Output: Map = {demo=1, demo=2}

      :Note → d1,d2,d3 are different Objects of demo class :
      :And are reffered to here as different keys :
      :For both HashMap and WeakHashMap :


      }
      }

      ```




B.Sorted Map - Interface

```mermaid

sequenceDiagram

java.util.SortedMap->>java.util.Map:extends

```

```Syntax

public interface SortedMap extends Map

```


  • SortedMap is an interface in the collection framework.


  • This interface extends the Map interface and provides a total ordering of its elements ,
    (elements can be traversed in sorted order of keys).


  • The class that implements this interface is TreeMap.




  • Methods of Sorted Map - Interface



    • 1.Comparator() - Example




    • 2.FirstKey()

    • ```Syntax
      Returns the first (lowest) key currently in this map.

      ```

    • 3.LastKey()

    • ```Syntax
      Returns the last (highest) key currently in this map.

      ```

    • 4.HeadMap(toKey:Key)

    • ```Syntax

      headMap(toKey:Key) :
      Returns a view of the portion of this map whose keys are strictly less than toKey.

      ```

    • 5.TailMap(fromKey:Key)

    • ```Syntax

      tailMap(fromKey:Key) :
      Returns a view of the portion of this map whose keys are greater than and equal to fromKey.

      ```

    • 6.SubMap(fromKey:Key, toKey:Key)

    • ```Syntax

      Returns a view of the portion of this map whose keys range from fromKey, inclusive,
      i.e. including fromKey and to toKey, exclusive i.e. excluding toKey.

      ```


      Methods
      Does This


      1.Comparator()

      A comparison function, which imposes a total ordering on some collection of objects.
      Comparators can also be used to control the order of sorted maps .
      Here,It returns the comparator used to order the keys in this map,
      or null if this map uses the natural ordering of its keys.


      2.FirstKey()

      Returns the first (lowest) key currently in this map.


      3.LastKey()

      Returns the last (highest) key currently in this map.

      4.HeadMap(toKey:Key)

      Returns a view of the portion of this map whose keys are strictly less than toKey.

      5.TailMap(fromKey:Key)

      Returns a view of the portion of this map whose keys are greater than and equal to fromKey.

      6.SubMap(fromKey:Key, toKey:Key)

      Returns a view of the portion of this map whose keys range from fromKey, inclusive,
      i.e. including fromKey and to toKey, exclusive i.e. excluding toKey.

      Note: SortedMap interface extends Map interface , hence it also inherits all functions from Map interface.




C.Navigable Map - Interface

```mermaid

sequenceDiagram

java.util.NavigableMap->>java.util.SortedMap:extends
java.util.SortedMap->>java.util.Map:extends

```

```Syntax

public interface NavigableMap extends SortedMap

public interface SortedMap extends Map

```


  • The NavigableMap interface is a member of the Java Collection Framework.


  • A NavigableMap can be easily accessed and traversed in either ascending or descending key order.


  • It belongs to java.util package and It is an extension of SortedMap which provides convenient navigation methods.



  • As it extends Sorted Map , hence methods of all Sorted Map interface can be accessed by Navigable Map .



  • These Navigation Methods are discussed below.



  • Methods of Navigable Map


    • 1.ceilingEntry

    • ```Syntax
      Returns a key-value mapping associated with the least key greater than
      or equal to the given key, or null if there is no such key.

      ```

    • 2.ceilingKey

    • ```Syntax
      Returns the least key greater than or equal to the given key,
      or null if there is no such key.

      ```

    • 3.descendingKeySet

    • ```Syntax
      Returns a reverse order NavigableSet view of the keys contained in this map.
      The set's iterator returns the keys in descending order.
      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:

      ```

    • 4.descendingMap

    • ```Syntax
      Returns a reverse order view of the mappings contained in this map.

      ```

    • 5.firstEntry

    • ```Syntax
      Returns a key-value mapping associated with the least key in this map,
      or null if the map is empty.

      ```

    • 6.floorEntry

    • ```Syntax
      Returns a key-value mapping associated with the greatest key less than
      or equal to the given key, or null if there is no such key.

      ```

    • 7.floorKey

    • ```Syntax
      Returns the greatest key less than or equal to the given key,
      or null if there is no such key.

      ```

    • 8.headMap(K toKey, boolean inclusive)

    • ```Syntax
      Returns a view of the portion of this map whose keys are less than
      (or equal to, if inclusive is true) toKey.

      if true:
      Returns a view of the portion of this map whose keys are equal to toKey,if inclusive is true.

      if false:
      Returns a view of the portion of this map whose keys are less than toKey,if inclusive is false.

      ```

    • 9.higherEntry

    • ```Syntax
      Returns a key-value mapping associated with the least key strictly greater than the given key,
      or null if there is no such key.

      ```

    • 10.higherKey

    • ```Syntax
      Returns the least key strictly greater than the given key, or null if there is no such key.

      ```

    • 11.lastEntry

    • ```Syntax
      Returns a key-value mapping associated with the greatest key in this map,
      or null if the map is empty.

      ```

    • 12.lowerEntry

    • ```Syntax
      Returns a key-value mapping associated with the greatest key strictly less than the given key,
      or null if there is no such key.

      ```

    • 13.lowerKey

    • ```Syntax
      Returns the greatest key strictly less than the given key, or null if there is no such key.

      ```

    • 14.navigableKeySet

    • ```Syntax

      Returns a NavigableSet view of the keys contained in this map.
      The set's iterator returns the keys in ascending order.
      The set is backed by the map, so changes to the map are reflected in the set, and vice-versa.
      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:

      ```

    • 15.pollFirstEntry

    • ```Syntax

      Removes and returns a key-value mapping associated with the least key in this map,
      or null if the map is empty.

      ```

    • 16.pollLastEntry

    • ```Syntax

      Removes and returns a key-value mapping associated with the greatest key in this map,
      or null if the map is empty.

      ```

    • 17.SubMap( fromKey:Key, boolean fromInclusive:true/false, toKey:Key, boolean toInclusive:true/false)

    • ```Syntax

      Returns a view of the portion of this map whose keys range from fromKey to toKey.
      If fromKey and toKey are equal, the returned map is empty
      unless fromInclusive and toInclusive are both true.

      ```

    • 18.tailMap(fromKey :Key, boolean inclusive: true/false)

    • ```Syntax

      Returns a view of the portion of this map whose keys are greater than,
      (or equal to, if inclusive is true) fromKey.

      ```


      Methods
      Does This

      1.ceilingEntry

      Returns a key-value mapping associated with the least key greater than
      or equal to the given key, or null if there is no such key.


      2.ceilingKey

      Returns the least key greater than or equal to the given key,
      or null if there is no such key.

      3.descendingKeySet

      Returns a reverse order NavigableSet view of the keys contained in this map.
      The set's iterator returns the keys in descending order.
      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.


      4.descendingMap

      Returns a reverse order view of the mappings contained in this map.

      5.firstEntry

      Returns a key-value mapping associated with the least key in this map,
      or null if the map is empty.

      6.floorEntry

      Returns a key-value mapping associated with the greatest key less than
      or equal to the given key, or null if there is no such key.

      7.floorKey

      Returns the greatest key less than or equal to the given key,
      or null if there is no such key.

      8.headMap(K toKey, boolean inclusive)

      Returns a view of the portion of this map whose keys are less than
      (or equal to, if inclusive is true) toKey.

      if true:
      Returns a view of the portion of this map whose keys are equal to toKey,if inclusive is true.

      if false:
      Returns a view of the portion of this map whose keys are less than toKey,if inclusive is false.

      9.higherEntry

      Returns a key-value mapping associated with the least key strictly greater than the given key,
      or null if there is no such key.

      10.higherKey

      Returns the least key strictly greater than the given key, or null if there is no such key.

      11.lastEntry

      Returns a key-value mapping associated with the greatest key in this map,
      or null if the map is empty.

      12.lowerEntry

      Returns a key-value mapping associated with the greatest key strictly less than the given key,
      or null if there is no such key.

      13.lowerKey

      Returns the greatest key strictly less than the given key, or null if there is no such key.

      14.navigableKeySet

      Returns a NavigableSet view of the keys contained in this map.
      The set's iterator returns the keys in ascending order.
      The set is backed by the map, so changes to the map are reflected in the set, and vice-versa.
      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.

      15.pollFirstEntry

      Removes and returns a key-value mapping associated with the least key in this map,
      or null if the map is empty.

      16.pollLastEntry

      Removes and returns a key-value mapping associated with the greatest key in this map,
      or null if the map is empty.

      17.SubMap( fromKey:Key, boolean fromInclusive:true/false, toKey:Key, boolean toInclusive:true/false)

      Returns a view of the portion of this map whose keys range from fromKey to toKey.
      If fromKey and toKey are equal, the returned map is empty
      unless fromInclusive and toInclusive are both true.

      18.tailMap(fromKey :Key, boolean inclusive: true/false)

      Returns a view of the portion of this map whose keys are greater than,
      (or equal to, if inclusive is true) fromKey.



Tree Map

    ```mermaid

    sequenceDiagram


    java.util.Map->>java.util.AbstractMap:implements
    java.util.AbstractMap->>java.util.TreeMap:extends
    java.util.Map->>java.util.SortedMap:extends
    java.util.SortedMap->>java.util.NavigableMap:extends
    java.util.NavigableMap->>java.util.TreeMap:implements
    java.io.Serializable->>java.util.TreeMap:implements
    java.lang.Cloneable->>java.util.TreeMap:implements
    ```

    ```Syntax

    public class TreeMap extends AbstractMap
    implements NavigableMap,Cloneable,Serializable

    public interface NavigableMap extends SortedMap

    public interface SortedMap extends Map

    ```

  • 1. The TreeMap in Java is used to implement Map interface .



  • 2. The TreeMap in Java is used to implement NavigableMap interface .



  • 3. The TreeMap in Java is used to extend the abstract class : "AbstractMap" .



  • 4.TreeMap in Java does not allow null keys (like Map) and thus a NullPointerException is thrown.



  • 5.Multiple null values can be associated with different keys in Tree Map.



  • 6.TreeMap contains only unique elements.



  • 7.TreeMap is non synchronized.



  • 8.TreeMap maintains ascending order. As Tree Map implements " Navigable Map" and Navigable Map extends Sorted Map.
    Hence tree map maintains sorted structure of map i.e. in ascending order.



  • 9." Entry pairs " returned by the methods in this class and its views represent snapshots of mappings at the time they were produced. " Entry.SetValue " is only supported when we try to change every specific values of the keys through a loop , But do not support the " Entry.setValue " method for individual entries.And they throw "Unsupported Operation Exception" .



  • 10.TreeMap is based upon a red-black tree data structure.( Red Black Trees are self-balancing, meaning that the tree adjusts itself automatically after each insertion or deletion operation. )




  • Constructors of TreeMap



    • 1.TreeMap()

    • ```Syntax
      It is used to construct a default constructor of TreeMap.

      It is used to construct an empty tree map,
      that will be sorted using the natural order of its key.

      ```

      2. TreeMap(Comparator super K> comparator)

      ```Syntax
      It is used to construct an empty tree-based map,
      that will be sorted using the comparator.

      ```

      • 2.a.TreeMap(Comparator super K> comparator)→Eg:1

      • ```Syntax

        Acc. to above eg:

        TreeMap2(no:1, name:"one", value:1)

        o1 and o2 are two object of TreeMap2,

        Therefore Comparison:

        o1.value - o2.value,
        i.e,1st Diff: 1-1 = 0

        TreeMap2(no:2, name:"two", value:2)

        Therefore Comparison:

        2nd Difference: 2-1 = 1

        TreeMap2(no:3, name:"three", value:3)

        o1.value: 3 - o2.value: 1 = 2

        o1.value: 3 - o2.value: 2 = 1

        TreeMap2(no:4, name:"four", value:4)

        o1.value: 4 - o2.value: 2 = 2

        o1.value: 4 - o2.value: 3 = 1

        Similary:
        TreeMap2(no:5, name:"five", value:5)

        o1.value: 5 - o2.value: 2 = 3

        o1.value: 5 - o2.value: 3 = 2

        o1.value: 5 - o2.value: 4 = 1

        ....etc.

        Hence:

        if we see the comparison:

        0 1 2 3 4 5 in ascending order.

        Hence Result is in ascending order.

        ```

      • 2.b.TreeMap(Comparator super K> comparator)→Eg:2

      • ```Syntax

        Acc. to above eg:

        TreeMap2(no:1, name:"one", value:1)

        o1 and o2 are two object of TreeMap2,

        Therefore Comparison:

        o2.value - o1.value,
        i.e,1st Diff: 1-1 = 0

        TreeMap2(no:2, name:"two", value:2)

        Therefore Comparison:

        2nd Difference: 1-2 = -1

        TreeMap2(no:3, name:"three", value:3)

        o2.value: 1 - o1.value: 3 = -2

        o2.value: 2 - o1.value: 1 = -1

        TreeMap2(no:4, name:"four", value:4)

        o2.value: 2 - o1.value: 4 = -2

        o2.value: 3 - o1.value: 4 = -1

        Similary:
        TreeMap2(no:5, name:"five", value:5)

        o2.value: 2 - o2.value: 5 = -3

        o2.value: 3 - o2.value: 5 = -2

        o2.value: 4 - o2.value: 5 = -1

        ....etc.

        Hence:

        if we see the comparison:

        -5 -4 -3 -2 -1 0 in descending order.

        Hence Result is in descending order.

        ```

    • 3.TreeMap(Map extends K,? extends V> m)

    • ```Syntax

      It is used to initialize a treemap with the entries from object of Map,
      which will be sorted using the natural order of the keys.

      ```

    • 4.TreeMap(SortedMap m)

    • ```Syntax

      It is used to initialize a treemap with the entries from object of SortedMap,
      which will be sorted using the natural order of the keys.

      ```

    • 5.TreeMap(NavigableMap m)

    • ```Syntax

      It is used to initialize a treemap with the entries from object of NavigableMap,
      which will be sorted using the natural order of the keys.

      Note : NavigableMap extends SortedMap
      And : TreeMap implements NavigableMap

      ```


      Constructor
      Does This


      1.TreeMap()

      It is used to construct a default constructor of TreeMap.

      It is used to construct an empty tree map,
      that will be sorted using the natural order of its key.


      2.TreeMap(Comparator super K> comparator)

      It is used to construct an empty tree-based map,
      that will be sorted using the comparator.


      3.TreeMap(Map extends K,? extends V> m)

      It is used to initialize a treemap with the entries from object of Map,
      which will be sorted using the natural order of the keys.

      4.TreeMap(SortedMap m)

      It is used to initialize a treemap with the entries from object of SortedMap,
      which will be sorted using the natural order of the keys.

      5.TreeMap(NavigableMap m)

      It is used to initialize a treemap with the entries from object of NavigableMap,
      which will be sorted using the natural order of the keys.

      Note : NavigableMap extends SortedMap,
      And : TreeMap implements NavigableMap.



    Methods of TreeMap



    • 1.TreeMap Methods



    • Note: These methods are already part of WeakHashMap , IdentityHashMap and HashMap .

    • 2.TreeMap Methods[Sorted Map Interface Methods]



    • Note: These methods are already part of Sorted Map Interface Methods, as TreeMap implements NavigableMap and NavigableMap extends SortedMap .

    • 3.TreeMap Methods[Navigable Map Interface Methods]

    • ```Syntax
      Suppose we have descendingKeySet() or navigableKeySet() functions:

      Then:

      The Set that will be produced by those function can be reserved in Set variable/object.

      1. Set set_var = TreeMap.navigableKeySet();

      2. Set set_var = TreeMap.descendingKeySet();

      Similary for Entry say, lastEntry() or pollFirstEntry():

      Then:

      It calls for Maps.Entry and reserves such entries under its variable/object.

      i.e.
      Import java.util.Map.Entry;
      Entry entry_var = TreeMap.pollLastEntry();

      or:
      Map.Entry entry_var = TreeMap.pollLastEntry();

      Similary for tailMap() or subMap() type Functions:

      They are always stored under the Map object/variable.

      i.e.

      Map map_var = TreeMap.tailMap(fromKey:Key, inclusive: true/false);

      If we want to store any key object then it can be store under it's type varibale:

      Eg:
      TreeMap treeMap = new TreeMap<>();
      Float float_var = treeMap.lowerKey(4.0f);

      ```


      Note: These methods are already part of Navigable Map Interface Methods, as TreeMap implements NavigableMap .



Synchronization of TreeMap




    The implementation of a TreeMap is not synchronized. This means that if multiple threads access a tree set concurrently, and at least one of the threads modifies the set, it must be synchronized externally. This is typically accomplished by using the Collections.synchronizedSortedMap method. Also it can be locked by synchronized() method and all such map objects can execute synchronized in a single thread.




Enum Map

```mermaid

sequenceDiagram

java.util.EnumMap->>java.util.AbstractMap:extends
java.util.EnumMap->>java.io.Serializable:implements
java.util.EnumMap->>java.io.Cloneable:implements
java.util.AbstractMap->>java.util.Map:implements
java.util.AbstractMap->>java.lang.Object:extends

```

```Syntax

public class EnumMap,​V>
extends AbstractMap
implements Serializable, Cloneable

public abstract class AbstractMap extends Object, implements Map

```


  • 1. EnumMap class is a member of the Java Collections Framework .



  • 2. EnumMap extends AbstractMap and AbstractMap (abstract class) implement Map Interface.



  • 3. EnumMap doesn’t allow null key and throws NullPointerException .



  • 4. All keys of each EnumMap instance must be keys of a single enum(enumeration) type.



  • 5.It’s a high-performance map implementation, much faster than HashMap.



  • 6.Iterators returned by the collection views are weakly consistent: they will never throw ConcurrentModificationException and they may or may not show the effects of any modifications to the map that occur while the iteration is in progress.



  • 7.EnumMap is internally represented as arrays. This representation is extremely compact and efficient.



  • Constructors of EnumMap


    • 1. EnumMap(Class keyType)

    • ```Syntax

      Creates an empty enum map with the specified key type.

      ```

    • 2. EnumMap(EnumMap m)

    • ```Syntax

      Creates an enum map with the same key type as the specified enum map,
      initially containing the same mappings (if any).

      ```

    • 3. EnumMap(Map m)

    • ```Syntax

      It is used to create an enum map initialized from the specified map.

      ```

      Constructor
      Does This


      1 . EnumMap(Class keyType)

      Creates an empty enum map with the specified key type.


      2 . EnumMap(EnumMap m)

      Creates an enum map with the same key type as the specified enum map,
      initially containing the same mappings (if any).

      3 . EnumMap(Map m)

      It is used to create an enum map initialized from the specified map.


    Methods of EnumMap



    • Methods of EnumMap

    • ```Syntax

      Note :

      Map.values() returns a Collection ,
      Hence the return value can be stored in object/variable of Collection.

      import java.util.Collection;
      Collection col_var =Map.values() ;

      ```


      Note: These methods are already discussed earlier.


D.ConcurrentMap -Interface

```mermaid

sequenceDiagram

java.util.concurrent.ConcurrentMap->>java.util.Map:extends

```

```Syntax

public interface ConcurrentMap extends Map

```


  • 1. ConcurrentMap is an interface and it is a member of the Java Collections Framework .


  • 2. ConcurrentMap is introduced in JDK 1.5 .


  • 3. ConcurrentMap represents a Map that is capable of handling concurrent access to the Map,without affecting the consistency of entries in a map .


  • 4. ConcurrentMap interface present in java.util.concurrent package .


  • 5. ConcurrentMap extends the Map interface in Java.


  • 6. ConcurrentMap is known as a synchronized Map.


  • 7. ConcurrentMap is implemented by ConcurrentSkipListMap and ConcurrentHashMap classes.


  • Methods of ConcurrentMap Interface


    • Methods of ConcurrentMap Interface

    • ```Syntax

      Note:

      For having all the entries of a Map as a Set:

      We have entrySet() function:

      It can be stored in Set's variable /object by:

      Either:

      Set> set_var = Map.entrySet();

      Or:

      import java.util.Map.Entry;

      Set> set_var = Map.entrySet();

      ```


      Note: These methods are already discussed earlier.

    New Methods Of ConcurrentMap



    • 1.Application of of() Method

    • ```Syntax

      Returns an unmodifiable map containing zero mappings.

      ```

    • 2.Application of of(1K,1V,..,nK,nV) Method

    • ```Syntax

      Returns an unmodifiable map containing 'N'mappings.

      ```

    • 3.Application of of(Map.Entry extends K,? extends V>… entries) Method

    • ```Syntax

      Returns an unmodifiable map containing keys and values,
      extracted from the given entries.
      The entries themselves are not stored in the map.

      ```


      New Methods
      Does This


      1.Application of of() Method
      Returns an unmodifiable map containing zero mappings.

      2.Application of of(1K,1V,..,nK,nV) Method
      Returns an unmodifiable map containing 'N'mappings.

      3.Application of of(Map.Entry extends K,? extends V>… entries) Method
      Returns an unmodifiable map containing keys and values,
      extracted from the given entries.
      The entries themselves are not stored in the map.


E.ConcurrentNavigableMap Interface

```mermaid

sequenceDiagram

java.util.concurrent.ConcurrentNavigableMap->>java.util.ConcurrentMap:extends
java.util.concurrent.ConcurrentNavigableMap->>java.util.NavigableMap:extends
java.util.concurrent.ConcurrentMap->>java.util.Map:extends
java.util.NavigableMap->>java.util.SortedMap:extends
java.util.SortedMap->>java.util.Map:extends

```

```Syntax

public interface ConcurrentNavigableMap extends ConcurrentMap
, NavigableMap

public interface ConcurrentMap extends Map
public interface NavigableMap extends SortedMap
public interface SortedMap extends Map

```


  • 1. The ConcurrentNavigableMap interface is a member of the Java Collection Framework .


  • 2. ConcurrentNavigableMap extends from the NavigableMap interface and ConcurrentMap interface .


  • 3. The ConcurrentNavigableMap provides thread-safe access to map elements along with providing convenient navigation methods .


  • 4. ConcurrentNavigableMap belongs to java.util.concurrent package.


  • 5. ConcurrentNavigableMap is SubInterface of ConcurrentMap interface .


  • 6. ConcurrentNavigableMap is also Synchronized , like ConcurrentMap interface .


  • 7. ConcurrentNavigableMap is implemented by ConcurrentSkipListMap class.


  • Methods of ConcurrentNavigableMap




    Note: The methods of ConcurrentNavigableMap Interface are inherited from SortedMap interface,,Map Interface,NavigableMap Interface and ConcurrentMap Interface.Hence some of them are discussed above.



ConcurrentHashMap

```mermaid

sequenceDiagram

java.util.concurrent.ConcurrentHashMap->>java.util.AbstractMap:extends
java.util.concurrent.ConcurrentHashMap->>java.util.concurrent.ConcurrentMap:implements
java.util.concurrent.ConcurrentHashMap->>java.io.Serializable:implements
java.util.concurrent.ConcurrentMap->>java.util.Map:extends
java.util.AbstractMap->>java.util.Map:implements
java.util.AbstractMap->>java.lang.Object:extends

```

```Syntax

public class ConcurrentHashMap extends AbstractMap
implements ConcurrentMap, Serializable

public interface ConcurrentMap extends Map

public abstract class AbstractMap extends Object implements Map

```

  • 1.The ConcurrentHashMap class is introduced in JDK 1.5 .

  • 2.The ConcurrentHashMap belongs to java.util.concurrent package.

  • 3.The ConcurrentHashMap class is thread-safe i.e. multiple threads can operate on a single object without any complications i.e Synchronization .

  • 4.Hashtable is thread safe but give poor performance in multi-threading.Hashmap can solve performance issue by giving parallel access to multiple threads reading hashmap simultaneously but Hashmap is not thread safe, hence ConcurrentHashMap is introduced in JDK 1.5. ConcurrentHashMap is thread safe ,it creates an array and each index of this array represents a HashMap. And Hashtable and HashMap both uses array and linkedlist as the data structure to store the data. Hence ,we can say, the underlined data structure for ConcurrentHashMap is Hashtable.

  • 5.The default concurrency-level of ConcurrentHashMap is 16.

  • 6.In ConcurrentHashMap, the Object is divided into a number of segments according to the concurrency level.

  • 7.In ConcurrentHashMap, at a time any number of threads can perform retrieval operation.

  • 8.In ConcurrentHashMap, to have a update in the object, the thread must lock the particular segment in which the thread wants to operate. This type of locking mechanism is known as Segment locking or bucket locking. Hence at a time, 16 update operations can be performed by threads as default concurrency-level of ConcurrentHashMap is 16.

  • 9.In ConcurrentHashMap, the higher the concurrency level, the more threads can access its buckets at once.

  • 10.In ConcurrentHashMap class is designed for use in concurrent data access,i.e. accessing data at same time.

  • 11.Inserting null objects is not possible in ConcurrentHashMap as a key or value.

  • 12.The ConcurrentHashMap doesn’t throw a ConcurrentModificationException if one thread tries to modify it while another is iterating over it.

  • ConcurrentHashMap

    ![1_N2ZCdgWnzlrWXczTvfvPFQ](https://user-images.githubusercontent.com/38869235/213485078-2c76b7f8-9ae8-4ffd-a6ab-e119049d64fa.png)

    In More Details

    ![1_U3oE8gg95rTulEJQGG10GQ](https://user-images.githubusercontent.com/38869235/213486273-c66acf6a-c65c-435e-bec7-abd6ebcef0d5.jpg)

    Note : Concurrent HashMap introduced parallelism threshold parameter, which says: "How many elements are needed for an operation to be executed in parallel, synchronized".

    Size of Segment Calculation


    Concurrency-Level: It is the number of threads concurrently updating the map.


    Segment in ConcurrentHashMap : In ConcurrentHashMap, the Object is divided into a number of segments according to the concurrency level.Each Segment has an Array of HashMap.



    [Segment Size = 2^x >=(initialCapacity / concurrencyLevel)]


    If concurrency level = 10

    Segment Size = 2^x >= 10

    if x= 3 then 2^3 >= 10
    = 8>=10 (Wrong)

    Then,

    x= 4 then 2^4 >= 10
    = 16>=10 (Right)

    Hence Segment Size = 16


    Constructors of ConcurrentHashMap



    • 1. ConcurrentHashMap()

    • ```Syntax

      Creates a new, empty map with a default initial capacity (16),
      load factor (0.75) and concurrencyLevel (16)

      Initial Capacity: Number of elements initially that a map can have.
      if the capacity of this map is 10. It means that it can store 10 entries.

      LoadFactor :
      The load factor is the measure that decides when to increase the capacity of the Map.
      It’s a threshold, used to control resizing of the Map.

      Concurrency-Level: It is the number of threads concurrently updating the map.
      The implementation performs internal sizing to try to accommodate this many threads.

      ```

    • 2. ConcurrentHashMap(initialCapacity)

    • ```Syntax

      Creates a new, empty map with an initial table size,
      accommodating the specified number of elements,
      without the need to dynamically resize.

      That is: Creates a new,
      empty map with the specified initial capacity,
      and with default load factor (0.75) and concurrencyLevel (16)

      ```

    • 3. ConcurrentHashMap(initialCapacity,loadFactor)

    • ```Syntax

      Creates a new empty map ,
      with an initial table size based on the given number of elements (initialCapacity)
      and initial table density (loadFactor).

      That is: Creates a new empty map ,
      with the specified initial capacity and
      load factor and with the default concurrencyLevel (16).

      ```

    • 4. ConcurrentHashMap(initialCapacity,loadFactor,concurrencyLevel)

    • ```Syntax

      Creates a new, empty map with an initial table size,
      based on the given number of elements (initialCapacity),
      table density (loadFactor), a
      nd number of concurrently updating threads (concurrencyLevel).

      That is: Creates a new, empty map
      with the specified initial capacity,
      load factor, and concurrency level

      ```

    • 5. ConcurrentHashMap(Map m)

    • ```Syntax

      Creates a new map with the same mappings as the given map.

      ```


    Methods of ConcurrentHashMap



    • 1. ConcurrentHashMap -- Methods


    • Note: Here methods discussed are inherited from ConcurrentMap,AbstractMap,Map interfaces.

      ```Syntax

      Note: Clone() method is not implemented by ConcurrentHashMap.
      It belongs to Abstract Map which is not visible to the class.
      If called then it throws exception : CloneNotSupportedException.
      There is a reason why Clone() method not implemented in ConcurrentHashMap.
      The reason is : ConcurrentHashMap is Thread Safe and
      creating a deep copy of the map would be difficult to implement .

      ```

      How to implement Clone method?


      New Methods of ConcurrentHashMap


      • 2. forEach​(long parallelismThreshold, BiFunction super K,​? super V,​? extends U> transformer, Consumer super U> action)

      • ```Syntax

        Performs the given action for each non-null transformation of each (key, value).

        The parallelismThreshold :
        It sets the number of items at which operations in a map begin to run concurrently.
        It determines whether bulk operations would be executed sequentially or in parallel.

        BiFunction: Represents a function that accepts two arguments and produces a result.

        Transformer: The transformer transforms the data before sending it to the Consumer.

        Consumer: It represents a functional interface which accepts
        a single input argument and produces no result.

        ```

      • 3. forEach​(long parallelismThreshold, BiConsumer super K,​? super V> action)

      • ```Syntax

        Performs the given action for each (key, value).

        The parallelismThreshold :
        It sets the number of items at which operations in a map begin to run concurrently.
        It determines whether bulk operations would be executed sequentially or in parallel.

        BiFunction: Represents a function that accepts two arguments and produces a result.

        ```

      • 4. forEachEntry​(long parallelismThreshold, Consumer super Map.Entry action)

      • ```Syntax

        Performs the given action for each (key, value).

        The parallelismThreshold :
        It sets the number of items at which operations in a map begin to run concurrently.
        It determines whether bulk operations would be executed sequentially or in parallel.

        Consumer: It represents a functional interface which accepts
        a single input argument and produces no result.

        ```

      • 5. forEachEntry​(long parallelismThreshold, Function,​? extends U> transformer, Consumer super U> action)

      • ```Syntax

        Performs the given action for each non-null transformation of each entry.

        The parallelismThreshold :
        It sets the number of items at which operations in a map begin to run concurrently.
        It determines whether bulk operations would be executed sequentially or in parallel.

        Function: It takes one argument and produces a result.

        Transformer: The transformer transforms the data before sending it to the Consumer.

        Consumer: It represents a functional interface which accepts
        a single input argument and produces no result.

        ```

      • 6. forEachKey​(long parallelismThreshold, Consumer super K> action)

      • ```Syntax

        Performs the given action for each non-null transformation of each entry.

        The parallelismThreshold :
        It sets the number of items at which operations in a map begin to run concurrently.
        It determines whether bulk operations would be executed sequentially or in parallel.

        Consumer: It represents a functional interface which accepts
        a single input argument and produces no result.

        ```

      • 7. forEachKey​(long parallelismThreshold, Function super K,​? extends U> transformer, Consumer super U> action)

      • ```Syntax

        Performs the given action for each non-null transformation of each key.

        The parallelismThreshold :
        It sets the number of items at which operations in a map begin to run concurrently.
        It determines whether bulk operations would be executed sequentially or in parallel.

        Function: It takes one argument and produces a result.

        Transformer: The transformer transforms the data before sending it to the Consumer.

        Consumer: It represents a functional interface which accepts
        a single input argument and produces no result.

        ```

      • 8. forEachKey​(long parallelismThreshold, Consumer super V> action)

      • ```Syntax
        Performs the given action for each value.

        The parallelismThreshold :
        It sets the number of items at which operations in a map begin to run concurrently.
        It determines whether bulk operations would be executed sequentially or in parallel.

        Consumer: It represents a functional interface which accepts
        a single input argument and produces no result.

        ```

      • 9. forEachValue​(long parallelismThreshold, Function super V,​? extends U>transformer, Consumer super U> action)

      • ```Syntax
        Performs the given action for each non-null transformation of each value.

        The parallelismThreshold :
        It sets the number of items at which operations in a map begin to run concurrently.
        It determines whether bulk operations would be executed sequentially or in parallel.

        Function: It takes one argument and produces a result.

        Transformer: The transformer transforms the data before sending it to the Consumer.

        Consumer: It represents a functional interface which accepts
        a single input argument and produces no result.

        ```

      • 10. keySet​(V mappedValue)

      • ```Syntax

        Returns a Set view of the keys in this map,
        using the given common mapped value for any additions
        (i.e., Collection.add and Collection.addAll(Collection)).
        This is of course only appropriate if it is acceptable ,
        to use the same value for all additions from this view.

        Which means if a Set's object is set to Map's keyset with
        its Mapped Value and if we continue to add with
        Collection.add () function through set the , added
        values will be refered as "Keys" of the map , automatically
        gets added to Map as "Keys" gets mapped with the given Value.

        Suppose we create an empty ConcurrentHashMap:

        ConcurrentHashMap map = new ConcurrentHashMap<>();

        Set set = map.keySet("1");
        set.add("one");
        System.out.println("Map:" + map);

        Output:

        Map:{one=1}

        Similarly,

        set = map.keySet("2");
        set.add("two");

        System.out.println("Map:" + map);

        Output:

        Map:{one=1, two=2}

        ....ETC.

        Same for set.addAll() Functionality ,but here ,

        Different keys will be assigned to Same Values.

        Set set2 =new HashSet<>();
        set2.add("three");
        set2.add("four");
        set.addAll(set2);
        System.out.println("Map:" + map);

        Output:

        Map:{one=1, two=2, three=2, four=2}

        As last mapped value was 2.

        ```

      • 11. MappingCount

      • ```Syntax

        Returns the number of mappings.

        This method should be used instead of size . The reason is,
        a ConcurrentHashMap may contain more mappings,
        than can be represented as an int.
        The value returned is an estimate;
        the actual count may differ ,
        if there are concurrent insertions or removals.

        ```

      • 12. newKeySet()

      • ```Syntax

        Creates a new Set backed by a ConcurrentHashMap,
        from the given type to Boolean.TRUE.

        ```

      • 13. newKeySet(int initialCapacity)

      • ```Syntax

        Creates a new Set backed by a ConcurrentHashMap,
        from the given type to Boolean.TRUE.

        ```

      • 14. reduce​(long parallelismThreshold, BiFunction super K,​? super V,​? extends U> transformer, BiFunction super U,​? super U,​? extends U> reducer)

      • ```Syntax

        Returns the result of accumulating the given transformation ,
        of all (key, value) pairs using the given reducer ,
        to combine values, or null if none.

        :Description of the Code is inside:

        ```

      • 15. reduceEntries​(long parallelismThreshold, BiFunction,​Map.Entry,​? extends Map.Entry> reducer)

      • ```Syntax

        Returns the result of accumulating all entries ,
        using the given reducer to combine values, or null if none.

        ```

      • 16. reduceEntries​(long parallelismThreshold, Function,​? extends U> transformer, BiFunction super U,​? super U,​? extends U> reducer)

      • ```Syntax

        Returns the result of accumulating the given transformation,
        of all entries using the given reducer to combine values,
        or null if none.

        ```

      • 17. reduceEntriesToDouble​(long parallelismThreshold, ToDoubleFunction> transformer, double basis, DoubleBinaryOperator reducer)

      • ```Syntax

        Returns the result of accumulating the given transformation ,
        of all entries using the given reducer to combine values,
        and the given basis as an identity value.

        ```

      • 18. reduceEntriesToInt​(long parallelismThreshold, ToIntFunction> transformer, int basis, IntBinaryOperator reducer)

      • ```Syntax

        Returns the result of accumulating the given transformation ,
        of all entries using the given reducer to combine values,
        and the given basis as an identity value.

        ```

      • 19. reduceEntriesToLong​(long parallelismThreshold, ToLongFunction> transformer, long basis, LongBinaryOperator reducer)

      • ```Syntax

        Returns the result of accumulating the given transformation,
        of all entries using the given reducer to combine values,
        and the given basis as an identity value.

        ```

      • 20. reduceKeys​(long parallelismThreshold, BiFunction super K,​? super K,​? extends K> reducer)

      • ```Syntax

        Returns the result of accumulating all keys ,
        using the given reducer to combine values,
        or null if none.

        ```

      • 21. reduceKeys​(long parallelismThreshold, Function super K,​? extends U> transformer, BiFunction super U,​? super U,​? extends U> reducer)

      • ```Syntax

        Returns the result of accumulating the given transformation,
        of all keys using the given reducer to combine values,
        or null if none.

        ```

      • 22. reduceKeysToDouble​(long parallelismThreshold, ToDoubleFunction super K> transformer, double basis, DoubleBinaryOperator reducer)

      • ```Syntax

        Returns the result of accumulating the given transformation,
        of all keys using the given reducer to combine values,
        and the given basis as an identity value.

        ```

      • 23. reduceKeysToInt​(long parallelismThreshold, ToIntFunction super K> transformer, int basis, IntBinaryOperator reducer)

      • ```Syntax

        Returns the result of accumulating the given transformation,
        of all keys using the given reducer to combine values,
        and the given basis as an identity value.

        ```

      • 24. reduceKeysToLong​(long parallelismThreshold, ToLongFunction super K> transformer, long basis, LongBinaryOperator reducer)

      • ```Syntax

        Returns the result of accumulating the given transformation,
        of all keys using the given reducer to combine values,
        and the given basis as an identity value.

        ```

      • 25. reduceToDouble​(long parallelismThreshold, ToDoubleBiFunction super K,​? super V> transformer, double basis, DoubleBinaryOperator reducer)

      • ```Syntax

        Returns the result of accumulating the given transformation of all
        (key, value) pairs using the given reducer to combine values,
        and the given basis as an identity value.

        ```

      • 26.reduceToInt​(long parallelismThreshold, ToIntBiFunction super K,​? super V> transformer, int basis, IntBinaryOperator reducer)

      • ```Syntax

        Returns the result of accumulating the given transformation of all (key, value) ,
        pairs using the given reducer to combine values,
        and the given basis as an identity value.

        ```

      • 27.reduceToLong​(long parallelismThreshold, ToLongBiFunction super K,​? super V> transformer, long basis, LongBinaryOperator reducer)

      • ```Syntax

        Returns the result of accumulating the given transformation of all
        (key, value) pairs using the given reducer to combine values,
        and the given basis as an identity value.

        ```

      • 28.reduceValues​(long parallelismThreshold, BiFunction super V,​? super V,​? extends V> reducer)

      • ```Syntax

        Returns the result of accumulating all values ,
        using the given reducer to combine values, or null if none.

        ```

      • 29.reduceValues​(long parallelismThreshold, Function super V,​? extends U> transformer, BiFunction super U,​? super U,​? extends U> reducer)

      • ```Syntax

        Returns the result of accumulating the given transformation ,
        of all values using the given reducer to combine values,
        or null if none.

        ```

      • 30.reduceValuesToDouble​(long parallelismThreshold, ToDoubleFunction super V> transformer, double basis, DoubleBinaryOperator reducer)

      • ```Syntax

        Returns the result of accumulating the given transformation,
        of all values using the given reducer to combine values,
        and the given basis as an identity value.

        ```

      • 31.reduceValuesToInt​(long parallelismThreshold, ToIntFunction super V> transformer, int basis, IntBinaryOperator reducer)

      • ```Syntax

        Returns the result of accumulating the given transformation,
        of all values using the given reducer to combine values,
        and the given basis as an identity value.

        ```

      • 32.reduceValuesToLong​(long parallelismThreshold, ToLongFunction super V> transformer, long basis, LongBinaryOperator reducer)

      • ```Syntax

        Returns the result of accumulating the given transformation of all values,
        using the given reducer to combine values, and
        the given basis as an identity value.

        ```

      • 33.search​(long parallelismThreshold, BiFunction super K,​? super V,​? extends U> searchFunction)

      • ```Syntax

        Returns a non-null result from applying the given,
        search function on each (key, value), or null if none.
        Upon success, further element processing is suppressed ,
        and the results of any other parallel invocations ,
        of the search function are ignored.

        ```

      • 34.searchEntries​(long parallelismThreshold, Function,​? extends U> searchFunction)

      • ```Syntax

        Returns a non-null result from applying the given,
        search function on each entry, or null if none.
        Upon success, further element processing is suppressed ,
        and the results of any other parallel invocations,
        of the search function are ignored.

        ```

      • 35.searchKeys​(long parallelismThreshold, Function super K,​? extends U> searchFunction)

      • ```Syntax

        Returns a non-null result from applying the given,
        search function on each entry, or null if none.
        Upon success, further element processing is suppressed ,
        and the results of any other parallel invocations,
        of the search function are ignored.

        ```

      • 36.searchValues​(long parallelismThreshold, Function super V,​? extends U> searchFunction)

      • ```Syntax

        Returns a non-null result from applying the given,
        search function on each entry, or null if none.
        Upon success, further element processing is suppressed ,
        and the results of any other parallel invocations,
        of the search function are ignored.

        ```

      • 37.Enumeration elements()

      • ```Syntax

        Returns an enumeration of the values in this table.

        ```

      • 38.Enumeration keys()

      • ```Syntax

        Returns an enumeration of the keys in this table.

        ```


        New Methods
        Does This


        1.forEach​(long parallelismThreshold, BiFunction super K,​? super V,​? extends U> transformer, Consumer super U> action)

        A comparison function, which imposes a total ordering on some collection of objects.
        Comparators can also be used to control the order of sorted maps .
        Here,It returns the comparator used to order the keys in this map,
        or null if this map uses the natural ordering of its keys.

        2.forEach​(long parallelismThreshold, BiConsumer super K,​? super V> action)

        Performs the given action for each (key, value).

        3.forEachEntry​(long parallelismThreshold, Consumer super Map.Entry action)

        Performs the given action for each (key, value).

        4.forEachEntry​(long parallelismThreshold, Function,​? extends U> transformer, Consumer super U> action)

        Performs the given action for each non-null transformation of each entry.

        5.forEachKey​(long parallelismThreshold, Consumer super K> action)

        Performs the given action for each non-null transformation of each entry.

        6.forEachKey​(long parallelismThreshold, Function super K,​? extends U> transformer, Consumer super U> action)

        Performs the given action for each non-null transformation of each key.

        7.forEachKey​(long parallelismThreshold, Consumer super V> action)

        Performs the given action for each value.

        8. forEachValue​(long parallelismThreshold, Function super V,​? extends U>transformer, Consumer super U> action)

        Performs the given action for each non-null transformation of each value.

        8. forEachValue​(long parallelismThreshold, Function super V,​? extends U>transformer, Consumer super U> action)

        Performs the given action for each non-null transformation of each value.

        9. keySet​(V mappedValue)

        Returns a Set view of the keys in this map,
        using the given common mapped value for any additions
        (i.e., Collection.add and Collection.addAll(Collection)).
        This is of course only appropriate if it is acceptable ,
        to use the same value for all additions from this view.

        Which means if a Set's object is set to Map's keyset with
        its Mapped Value and if we continue to add with
        Collection.add () function through set the , added
        values will be refered as "Keys" of the map , automatically
        gets added to Map as "Keys" gets mapped with the given Value.

        10. MappingCount

        Returns the number of mappings. This method should be used instead of size . The reason is, a ConcurrentHashMap may contain more mappings,
        than can be represented as an int. The value returned is an estimate; the actual count may differ ,if there are concurrent insertions or removals.

        11. newKeySet()

        Creates a new Set backed by a ConcurrentHashMap,from the given type to Boolean.TRUE.

        12. newKeySet(int initialCapacity)

        Creates a new Set backed by a ConcurrentHashMap,from the given type to Boolean.TRUE.

        13. reduce​(long parallelismThreshold, BiFunction super K,​? super V,​? extends U> transformer, BiFunction super U,​? super U,​? extends U> reducer)

        Returns the result of accumulating the given transformation ,of all (key, value) pairs using the given reducer ,to combine values, or null if none.

        14. reduceEntries​(long parallelismThreshold, BiFunction,​Map.Entry,​? extends Map.Entry> reducer)

        Returns the result of accumulating all entries ,using the given reducer to combine values, or null if none.

        15. reduceEntries​(long parallelismThreshold, Function,​? extends U> transformer, BiFunction super U,​? super U,​? extends U> reducer)

        Returns the result of accumulating the given transformation,of all entries using the given reducer to combine values, or null if none.

        16. reduceEntriesToDouble​(long parallelismThreshold, ToDoubleFunction> transformer, double basis, DoubleBinaryOperator reducer)

        Returns the result of accumulating the given transformation ,of all entries using the given reducer to combine values, and the given basis as an identity value.

        17. reduceEntriesToInt​(long parallelismThreshold, ToIntFunction> transformer, int basis, IntBinaryOperator reducer)

        Returns the result of accumulating the given transformation ,of all entries using the given reducer to combine values, and the given basis as an identity value.

        18. reduceEntriesToLong​(long parallelismThreshold, ToLongFunction> transformer, long basis, LongBinaryOperator reducer)

        Returns the result of accumulating the given transformation,of all entries using the given reducer to combine values, and the given basis as an identity value.

        19.reduceKeys​(long parallelismThreshold, BiFunction super K,​? super K,​? extends K> reducer)

        Returns the result of accumulating all keys ,using the given reducer to combine values, or null if none.

        20.reduceKeys​(long parallelismThreshold, Function super K,​? extends U> transformer, BiFunction super U,​? super U,​? extends U> reducer)

        Returns the result of accumulating the given transformation,of all keys using the given reducer to combine values, or null if none.

        21. reduceKeysToDouble​(long parallelismThreshold, ToDoubleFunction super K> transformer, double basis, DoubleBinaryOperator reducer)

        Returns the result of accumulating the given transformation,of all keys using the given reducer to combine values, and the given basis as an identity value.

        22. reduceKeysToInt​(long parallelismThreshold, ToIntFunction super K> transformer, int basis, IntBinaryOperator reducer)

        Returns the result of accumulating the given transformation,of all keys using the given reducer to combine values, and the given basis as an identity value.

        23.reduceKeysToLong​(long parallelismThreshold, ToLongFunction super K> transformer, long basis, LongBinaryOperator reducer)

        Returns the result of accumulating the given transformation,of all keys using the given reducer to combine values, and the given basis as an identity value.

        24.reduceToDouble​(long parallelismThreshold, ToDoubleBiFunction super K,​? super V> transformer, double basis, DoubleBinaryOperator reducer)

        Returns the result of accumulating the given transformation of all (key, value) pairs using the given reducer to combine values,and the given basis as an identity value.

        25. reduceToInt​(long parallelismThreshold, ToIntBiFunction super K,​? super V> transformer, int basis, IntBinaryOperator reducer)

        Returns the result of accumulating the given transformation of all (key, value) ,pairs using the given reducer to combine values, and the given basis as an identity value.

        26. reduceToLong​(long parallelismThreshold, ToLongBiFunction super K,​? super V> transformer, long basis, LongBinaryOperator reducer)

        Returns the result of accumulating the given transformation of all (key, value) pairs using the given reducer to combine values, and the given basis as an identity value.

        27. reduceValues​(long parallelismThreshold, BiFunction super V,​? super V,​? extends V> reducer)

        Returns the result of accumulating all values ,using the given reducer to combine values, or null if none.

        28. reduceValues​(long parallelismThreshold, Function super V,​? extends U> transformer, BiFunction super U,​? super U,​? extends U> reducer)

        Returns the result of accumulating the given transformation ,of all values using the given reducer to combine values, or null if none.

        29. reduceValuesToDouble​(long parallelismThreshold, ToDoubleFunction super V> transformer, double basis, DoubleBinaryOperator reducer)

        Returns the result of accumulating the given transformation,of all values using the given reducer to combine values, and the given basis as an identity value.

        30. reduceValuesToInt​(long parallelismThreshold, ToIntFunction super V> transformer, int basis, IntBinaryOperator reducer)

        Returns the result of accumulating the given transformation,of all values using the given reducer to combine values, and the given basis as an identity value.

        31. reduceValuesToLong​(long parallelismThreshold, ToLongFunction super V> transformer, long basis, LongBinaryOperator reducer)

        Returns the result of accumulating the given transformation of all values,using the given reducer to combine values, and the given basis as an identity value.

        32.search​(long parallelismThreshold, BiFunction super K,​? super V,​? extends U> searchFunction)

        Returns a non-null result from applying the given,search function on each (key, value), or null if none. Upon success, further element processing is suppressed ,and the results of any other parallel invocations ,of the search function are ignored.

        33. searchEntries​(long parallelismThreshold, Function,​? extends U> searchFunction)

        Returns a non-null result from applying the given,search function on each entry, or null if none.Upon success, further element processing is suppressed ,and the results of any other parallel invocations,of the search function are ignored.

        34. searchKeys​(long parallelismThreshold, Function super K,​? extends U> searchFunction)

        Returns a non-null result from applying the given,search function on each entry, or null if none.Upon success, further element processing is suppressed ,and the results of any other parallel invocations,of the search function are ignored.

        35. searchValues​(long parallelismThreshold, Function super V,​? extends U> searchFunction)

        Returns a non-null result from applying the given,search function on each entry, or null if none.Upon success, further element processing is suppressed ,and the results of any other parallel invocations,of the search function are ignored.

        36. Enumeration elements()

        Returns an enumeration of the values in this table.

        37. Enumeration keys()

        Returns an enumeration of the keys in this table.


      ConcurrentHashMap.KeySetView - Inner Class of ConcurrentHashMap

      ```mermaid

      sequenceDiagram

      java.util.concurrent.ConcurrentHashMap->>java.util.ConcurrentHashMap.KeySetView:InnerClass
      java.util.ConcurrentHashMap.KeySetView->>java.util.concurrent.ConcurrentHashMap.CollectionView:extends
      java.util.ConcurrentHashMap.KeySetView->>java.util.Set:implements
      java.util.ConcurrentHashMap.KeySetView->>java.io.Serializable:implements

      ```

      ```Syntax

      public class ConcurrentHashMap extends AbstractMap
      implements ConcurrentMap, Serializable {

      ......

      public static final class KeySetView extends CollectionView
      implements Set, java.io.Serializable

      ....

      }

      ```


      • 1. CollectionView class is an abstract class of ConcurrentHashMap class which is not viable or be imported to any file . Syntax as follows:
      • ```Syntax

        abstract static sealed class CollectionView
        implements Collection, java.io.Serializable
        permits EntrySetView, KeySetView, ValuesView

        ```


      • 2. More Over EntrySetView, KeySetView and ValuesView are "Static Final Classes" of "ConcurrentHashMap" class and are not viable or be imported to any file. Syntax as follows:
      • EntrySetView Class

        ```Syntax

        static final class EntrySetView extends
        CollectionView>
        implements Set>, java.io.Serializable

        ```

        KeySetView Class

        ```Syntax

        public static final class KeySetView extends CollectionView
        implements Set, java.io.Serializable

        ```

        ValuesView Class

        ```Syntax

        static final class ValuesView extends CollectionView
        implements Collection, java.io.Serializable

        ```


      • 3. CollectionView class, EntrySetView class, KeySetView class and ValuesView class cannot be implemented directly but can be implemented through KeySetView as KeySetView , the inner class of ConcurrentHashMap class inherit those classes along with Set and Serializable interface.

      • 4. The main motive of KeySetView , the inner class of ConcurrentHashMap to store the Keys of the given Map as a Set in a Variable or object created by KeySet class or ConcurrentHashMap.KeySet class.

      • Implementation of ConcurrentHashMap.KeySetView class












      • 2. ConcurrentHashMap.KeySetView-Eg(2)


ConcurrentSkipListMap


    ```mermaid

    sequenceDiagram

    java.util.concurrent.ConcurrentSkipListMap->>java.lang.Cloneable:implements
    java.util.concurrent.ConcurrentSkipListMap->>java.io.Serializable:implements
    java.util.concurrent.ConcurrentSkipListMap->>java.util.concurrent.ConcurrentNavigableMap:implements
    java.util.concurrent.ConcurrentSkipListMap->>java.util.AbstractMap:extends
    java.util.concurrent.ConcurrentNavigableMap->>java.util.ConcurrentMap:extends
    java.util.concurrent.ConcurrentNavigableMap->>java.util.NavigableMap:extends
    java.util.concurrent.ConcurrentMap->>java.util.Map:extends
    java.util.NavigableMap->>java.util.SortedMap:extends
    java.util.SortedMap->>java.util.Map:extends
    java.util.AbstractMap->>java.util.Map:implements
    java.util.AbstractMap->>java.lang.Object:extends

    ```

    ```Syntax

    public class ConcurrentSkipListMap extends AbstractMap
    implements ConcurrentNavigableMap, Cloneable, Serializable

    public abstract class AbstractMap extends Object implements Map

    public interface ConcurrentNavigableMap extends ConcurrentMap
    , NavigableMap

    public interface ConcurrentMap extends Map
    public interface NavigableMap extends SortedMap
    public interface SortedMap extends Map

    ```


    • 1.The ConcurrentSkipListMap class is a member of the Java Collections Framework.



    • 2.The ConcurrentSkipListMap was introduced in JDK 1.6.



    • 3.The ConcurrentSkipListMap belongs to java.util.concurrent package.



    • 4.The ConcurrentSkipListMap is a scalable implementation of ConcurrentNavigableMap.



    • 5.All the elements of ConcurrentSkipListMap sorted based on natural ordering or by the Comparator passed during it’s construction time.



    • 6.This class uses a concurrent variation of SkipList data structure providing log(n) time cost for insertion, removal, update, and access operations.



    • 7.These operations are safe for executing concurrently by multiple threads. (ConcurrentSkipListMap is thread-safe.)



    Constructors of ConcurrentSkipListMap


    • 1.ConcurrentSkipListMap()

    • ```Syntax

      Constructs a new, empty map, sorted according to the natural ordering of the keys.

      ```

    • 2.ConcurrentSkipListMap​(Comparator super K> comparator)

      • 2.a.ConcurrentSkipListMap​(Comparator super K> comparator)

      • ```Syntax

        Constructs a new, empty map, sorted according to the specified comparator.

        Note:

        1. ConcurrentSkipListMap map =
        new ConcurrentSkipListMap<>((a, b) -> b.compareTo(a))

        2. Comparator super Key> comparator = map.comparator();

        ConcurrentSkipListMap map =
        new ConcurrentSkipListMap<>(comparator)

        ```

      • 2.b.ConcurrentSkipListMap​(Comparator super K> comparator)

      • ```Syntax

        Constructs a new, empty map, sorted according to the specified comparator.

        Here Class implements Comparator interface for comparison.

        Generally negative comparison : ReverseOrder

        Generally positive comparison : AscendingOrder/NaturalOrder

        ```

      • 2.c.ConcurrentSkipListMap​(Comparator super K> comparator)

      • ```Syntax

        Constructs a new, empty map, sorted according to the specified comparator.

        Here Comparator object is passed inside Constructor.

        Generally negative comparison : ReverseOrder

        Generally positive comparison : AscendingOrder/NaturalOrder

        ```

      • 2.d.ConcurrentSkipListMap​(Comparator super K> comparator)

      • ```Syntax

        Constructs a new, empty map, sorted according to the specified comparator.

        Here Direct Comparator Class is called inside Constructor.

        Comparator.reverseOrder(): Gives Reverse Order of Values
        Comparator.naturalOrder(): Gives Natural Order of Values

        Any negative comparison : ReverseOrder

        Any positive comparison : AscendingOrder/NaturalOrder

        ```

    • 3.ConcurrentSkipListMap​(Map extends K,​? extends V> m)

    • ```Syntax

      Constructs a new map containing the same mappings as the given map,
      sorted according to the natural ordering of the keys.​

      ```

    • 4.ConcurrentSkipListMap​(SortedMap m)

    • ```Syntax

      Constructs a new map containing the same mappings and
      using the same ordering as the specified sorted map.

      ```


      Methods of ConcurrentSkipListMap




F. Map.Entry Interface (Sub Interface of Map Interface) and Map.of()



HashTable Class


    ```mermaid

    sequenceDiagram

    java.util.HashTable->>java.util.Dictionary:extends
    java.util.HashTable->>java.util.Map:implements
    java.util.HashTable->>java.io.Serializable:implements
    java.util.HashTable->>java.lang.Cloneable:implements

    ```

    ```Syntax

    public class Hashtable extends Dictionary
    implements Map, Cloneable, Serializable

    ```

    Note : Details of HashTable class is explained 👉 Link Here



👉Implementation of Map in Java Generics