All Classes and Interface of Map Interface

 In Java, the Map interface is a top-level interface, that does not extends the Iterable and Collection interface. The map interface represents a collection as a key-value pair.

Extends/Implemented classes and interface - 
  1. HashMap   (extended in LinkedHashMap)
  2. SortedMap (implemented in TreeMap)


1. HashMap Class: The HashMap is used to store as key-values pair without any specific ordering of keys. 
  • Does not maintain any order of the key.
  • Provides constant-time performance for basic operation like - put(), get(), remove().
  • Allows one null key, and multiple null values.
Use Case: When we need fast access based on a unique key and the order of keys is not important then we can use it. For example, use to cache the data on the unique key.

HashMap class code example

2. LinkedHashMap Class: LinkedHashMap extends the HashMap and maintains the order of elements based on insertion.
  • Maintains the order of keys
  • Slightly slower than HashMap
  • Allows one null key and multiple null values
Use Case: When we need to store the elements as key-value and order of the elements then we can use it.

LinkedHashMap class code example

3. SortedMap: SortedMap extends the Map interface. It stores the elements as key values pair with the sorting of elements. By default, it does Natural sorting (Lower to Highest) but it can reverse sorting using the Comparator class.
  • Keys are maintained in sorted order.
  • Provides additional methods. Like - firstKey(), lastKey(), headMap(), tailMap(), subMap() to navigate through the map.
Use Case: Used when we need a map with a sorted key set.

SortedMap interface code example

4. TreeMap: TreeMap implements the SortedMap interface. It stores key-value pairs in a Red-Black tree.
  • Maintain sorted order keys
  • Slower than HashMap
  • Does not allow null keys, but allows null values
Use Case: We can use it to decorate the Menu of web application.

TreeMap class code example











Post a Comment

0 Comments