Map interface in Java
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.
- HashMap (class): HashMap uses to store the data using hashing technique. HashMap contains unique keys only. It is non-synchronized.
- LinkedHashMap (Interface): It is the same as HashMap only difference is to preserve the insertion order.
- 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 .
- 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