Introduction to HashMap in Java.
Hi everyone, thanks in advance for taking time to read my very first blog. I started learning JAVA recently and it kept me hooked, so I decided to start my blogging journey with my recent fascination.
I will talk about HashMap in JAVA.
HashMap is a class of Java Collection Framework which is about Key to Value mapping. It stores data in form of key and values. It is hash table based implementation of Java Map interface. In simple language, it stores items with identifiers, it is denoted as
HashMap<Key, Value> or HashMap<K, V>
I will try to illustrate the same with an example for better understanding
HashMap<String, String>capitalmap = new HashMap<String, String>()
capitalmap.put (“India”, “Delhi”);
capitalmap.put (“USA”, “Washington D.C”);
capitalmap.put (“U.K”, “London”);
capitalmap.put (“Russia”, “null”);
capitalmap.put (“Israel”, “null”);
capitalmap.put (“null”, “Berlin”);
In the above, we are using the Put method to store the data in the HashMap wherein the Key, K = India and the Value, V = Delhi
Some important features of HashMap are mentioned as below:
· HashMap stores values based on the key.
· Java HashMap contains only unique keys.
· There can be n number of null values in the HashMap, however, only one null key is allowed. Incase we store more, then the latest null value shall be displayed means it will be Overridden.
· Duplication is not a feature of HashMap, cannot have duplicate keys.
capitalmap.put (“U.K” , “London”);
capitalmap.put (“U.K” , “England”);
In the above example, the latest value will be published which is “England”
· HashMap does not maintain any order, it is an unordered collection, however, if sorting is required then the user need to do it explicitly as required. It can be done either using
§ Sort by Keys
§ Sort by Values
· It is not synchronized but user can synchronize it externally with the help of Collections.
· HashMap is faster but is not thread safe hence cannot be shared between many threads without proper synchronization code.
· Size of the HashMap gives the number of entries or pairs of key-values in the map and can be found by using the following:
capitalmap. size;
Methods which are widely used in Java HashMap
1. putIfAbsent (K key, V value) method is used to insert key or value in the existing HashMap
2. To Remove user can simply use
capitalmap. remove(“London”);
3. To remove All then
capitalmap. clear;
Contains Key/Value Method helps in knowing if the element is there in the map
4. To use the get method, following syntax can be used
Hash_Map.get(Object key_element)Below is an illustrated example for the same:
System.out.println(capitalmap.get (“India”)); then run
key = India, Value=Delhi
In my future blogs, I will talk about What is HashTable and how it is different from HashMap.