MultiMap in Java

Java 8Server Side ProgrammingProgramming

Multimap is a general method to bind the keys with random multiple values. The Multimap framework in Guava has methods that help in dealing with mapping keys to multiple values. Multimap can be visualized as a framework that −

  • Is a collection of mapping from one key to one specific value
  • Is a collection of mapping from unique key to multiple values, i.e. collection of values.

It can be implemented in places that use Map<K, Collection<V>>.

Advantages of Multimap

  • An empty collection need not be populated before added a key value pair with the help of the function ‘put’.
  • The ‘get’ method doesn’t return a null, except for cases of empty collection.
  • A key is present in Multimap if and only if it has been mapped to at least one value.
  • If a key in a multimap has no associated values, that key is removed implicitly from multimap.
  • The number of values in the multimap can be obtained with the help of the function ‘size’.

Certain functions in Multimap −

  • Multimap.containsKey(key) − This function returns a true when there is an element/mapping associated with the key that is passed as a parameter to this function. Otherwise, this function returns false.
  • Multimap.entries() − This function returns all the associated values for all the keys with respect to the multimap.

Note − If we wish to obtain the entries as a key-value pair, the ‘asMap().entrySet()’ can be used. Multimap.size(): This function returns the total number of entries in the Multimap in its entirety. It doesn’t give the distinct keys, just all of them.

Distinct keys can be obtained by using the Multimap.keySet().size().

raja
Published on 14-Sep-2020 12:21:49
Advertisements