Java HashMap

HashMap is a class which implements Map interface.

Map collection used to store data in key value pair. 

It doesn’t maintain insertion order which means there is no guarantee for the order of key value pair while accessing the HashMap.

HashMap is similar to the Hashtable class except HashMap allows multiple null values and the null key. 

HashMap contains only unique keys. The addition of a duplicate key will not throw an exception and will replace it with the last added item.

Also, the HashMap is unsynchronized which means multiple threads can access the HashMap at the same time and change its value in comparison of Hashtable which is synchronized and make it as a low performer as single thread can access Hashtable at the same time.

HashMap belongs to java.util.HashMap package.

Syntax:

HashMap<K, V>()

HashMap<K, V>(int initialCapacity, loadFactor)

HashMap Constructors

HashMap provides below four contructors to create its insatance:

  1. HashMap() → This will creates an instance of HashMap with an initial capacity of 16 and load factor of 0.75.
  2. HashMap(Map map) → This will create a instance of HashMap using existing map.
  3. HashMap(int initialCapacity) → This will creates an instance of HashMap with defined capacity and load factor of 0.75.
  4. HashMap(int initialCapacity, float loadFactor) → This will creates an instance of HashMap with an initial capacity and load factor.

Example:

HashMap Methods:

Below are the methods define in HashMap which will help us to add, delete, get, contains, clear etc. values in HashMap.

HashMap Sorting:

For sorting a Map we will be using List which provides us Collections.sort() method for sorting elements within the list. Comparator interface from java.util.* package will help us to compare or sort values using compare method.

Below code is performing sorting on map values.

Imran Khan

Specialist Master (Architect) with a passion for cutting-edge technologies like AEM (Adobe Experience Manager) and a proven track record of delivering high-quality software solutions.

  • Languages: Java, Python
  • Frameworks: J2EE, Spring, Struts 2.0, Hibernate
  • Web Technologies: React, HTML, CSS
  • Analytics: Adobe Analytics
  • Tools & Technologies: IntelliJ, JIRA

🌐 LinkedIn

📝 Blogs

📧 Imran Khan