Map interface in Java

Kiran Kumar
2 min readMar 26, 2022

--

Lets understand Map interface and its implementation with some use cases

Map(Interface): It stores the data into key-value pairs. The map is not in the hierarchy of collection it is different from it. It doesn’t implement the collection interface. The duplicate value is not allowed in it.

ref: google images
  1. HashMap (class): HashMap uses to store the data using hashing technique. HashMap contains unique keys only. It is non-synchronized.
  2. LinkedHashMap (Interface): It is the same as HashMap only difference is to preserve the insertion order.
  3. TreeMap (class): It uses to implement the Navigable interface and can use all its method. TreeMap is basically responsible for the Sorting order. By default, it sorts in ascending order as per keys. It doesn’t allow duplicate values and not that null values too.

In above example you can observe the if keys are added twice to map , it will be overridden .

  1. How to iterate Map with using entrySet()

2. Looping using LinkedHashMap , it maintains insertion order

Null pointer exception while assigning null key to TreeMap , as it orders while inserting itself , we cannot sort TreeMap as behaviour of sort element without null keys in map

--

--

Kiran Kumar

Technophile with 10 years experience in IT industry | Java Lead cum Architect