Java HashMap | Constructors & Methods of HashMap in Java

Free Java courses with 37 real-time projects - Learn Java

1. HashMap in Java

Today, in this Java HashMap tutorial, we are going to learn about the HashMap in Java. First, we will start with the meaning of Java HashMap. Moreover, we will learn constructors and methods in HashMap in Java. Also, we will discuss Java HashMap example and the internal structure of HashMap in Java.

So, let us start Java HashMap Tutorial.

Java HashMap

Java HashMap | Constructors & Methods of HashMap in Java

2. What is Java HashMap?

Java HashMap permits null key and null values.

HashMap isn’t an ordered collection. You’ll be able to iterate over HashMap entries through keys set however they’re not guaranteed to be within the order of their addition to the HashMap.

Do you know What is Inheritance in Java?

HashMap in Java uses its inner category Node for storing map entries.

Java Hashmap stores entries into multiple one by one linked lists which are called buckets or bins. Default range of bins is 16 and it’s always a power of 2.

HashMap uses hashCode() and equals() ways on keys to get and place operations. Therefore HashMap key object should offer good implementation of those ways. This can be the reason immutable classes are higher suitable for keys, for example, String and Integer.

Java HashMap isn’t thread-safe, for the multithreaded environment, you must use ConcurrentHashMap category or get a synchronous map using Collections.synchronizedMap() method.

Let’s discuss Methos Overriding in Java

3. Java HashMap Constructors

HashMap in Java provides four constructors. So, below we are discussing 4 constructors in Java HashMap tutorial:

a. public HashMap(): Most commonly used HashMap constructor. This constructor can produce an empty HashMap with default initial capacity 16 and load factor 0.75

b. public HashMap(int initialCapacity): This HashMap constructor is used to specify the initial capacity and 0.75 ratio. This can helps in avoiding rehashing if you know the number of mappings to hold HashMap.

c. public HashMap(int initialCapacity, float loadFactor): This HashMap constructor can produce an empty HashMap with specified initial capacity and load factor.

d. public HashMap(Map<? extends K, ? extends V> m): Creates a Map having same mappings because of the specified map and with load factor 0.75
Example of Java HashMap Constructors

Below code snippet is showing constructor of HashMap in Java example of victimization all the above constructors.

Let’s learn Java File Class

Map map1 = new HashMap<>();
Map map2 = new HashMap<>(2^5);
Map map3 = new HashMap<>(32,0.80f);
Map map4 = new HashMap<>(map1);

4. Methods of HashMap in Java

i. Important methods of Java HashMap

Let’s have a look at the important methods of Java HashMap:

a. public void clear(): This Java HashMap method will remove all the mappings and HashMap will become empty.

b. public boolean containsKey(Object key): This Hashmap in Java method returns ‘true’ if the key exists otherwise it will return ‘false’.

c. public mathematician containsValue(Object value): This Java HashMap method returns true if the value exists.

d. public Set> entrySet(): This Hashmap Method in Java returns a set view of the HashMap mappings.

e. public V get(Object key): This Java Hashmap Method Returns the value mapped to the specified key, or null if there’s no mapping for the key.

f. public boolean isEmpty(): A utility method returning true if no key-value mappings are present.

Let’s see Java Interface

g. public Set keySet(): Returns a set view of the keys contained in this map. The set is backed by the map, so changes to the map are reflected within the set, and vice-versa.

h. public V put(K key, V value): This method associates the specified value with the specified key in this map and if the map previously contained a mapping for the key, the old value is replaced.

i. public void putAll(Map<? extends K, ? extends V> m): Copies all of the mappings from the required map to the present map. These mappings can replace any mappings that this map had for any of the keys currently within the specified map.

j. public V remove(Object key): This Java HashMap method helps remove the mapping for the required key from this map if present.

k. public int size(): This method in Hashmap in Java helps return the number of key-value mappings in this map.

l. public Collection values(): This method of Hashmap in Java helps returns a collection view of the values contained in this map. The collection is backed by the map, so changes to the map are reflected in the collection, and vice-versa.

ii. New Methods of Java HashMap

Many new methods in Java HashMap introduced in Java 8, let us have a look at them –

a. public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction): If the specified key is not already associated with a value (or is mapped to null), this method tries to reason its value using the given mapping function and therefor enters it into the HashMap unless it is Null.

b. public V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction): In this method, if the value for the required key is present and non-null, it, therefore, tries to reason a replacement mapping given the key and its current mapped value.

Read Java Packages

c. public V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction): This HashMap method attempts to compute a mapping for the required key and its current mapped value.

d. public void forEach(BiConsumer<? super K, ? super V> action): This method performs the given action for each entry in this map.

e. public V getOrDefault(Object key, V defaultValue): Same as get except that defaultValue is returned if no mapping found for the specified key.

f. public V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction): If the required key is not already related to a value or is associated with null, associates it with the given non-null value.

g. public V putIfAbsent(K key, V value): In this method, if the specified key is not already associated with a value (or is mapped to null) associates it with the given value and returns null, else returns this price.

h. public boolean remove(Object key, Object value): In this method, it removes the entry for the specified key only if it’s currently mapped to the specified value.

i. public boolean replace(K key, V oldValue, V newValue): RIN this method it helps to replace the entry for the specified key only if currently mapped to the specified value.

j. public V replace(K key, V value): In this method, it helps to replace the entry for the specified key only if it currently map to some value.

Let’s explore Java SerDe

k. public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function): In this method, it helps replace every entry’s value with the result of invoking the given function on that entry.

5. Java HashMap – Internal Structure

Internal Structure of Java Hashmap contains these four nodes of the array, and further, the node represents with the help of a class –
i. int hash
ii. K key
iii. V value
iv. Node next
A node contains a reference to its own object and hence it is a linked list.

Java Hashmap - Internal Structures

Hashmap in Java – Internal Structures


Java HashMap

HashMap in Java

a. Performance of HashMap

Performance of Java HashMap depends on these two factors –

i. Initial Capacity

ii. Load Factor

In a Java HashMap, the capacity simply defines as the number of buckets, while the Initial capacity of HashMap in Java define when it we craete it initially. Further, we multiply capacity with 2.

In a Load Factor, a measure of much rehashing is to do. It is also a measure of how much rehashing to do. It is initially kept higher so rehashing doesn’t take place, but this also increases the iteration time. The most common load factor value is 0.75. It varies from 0- 1.

Let’s learn about Abstract Class in Java

Example of Java HashMap performance–

import java.util.HashMap;
import java.util.Map;
public class DF
   public static void main(String[] args)
       HashMap<String, Integer> map = new HashMap<>();
       map.put("vishal", 10);
       map.put("sachin", 30);
       map.put("vaibhav", 20);
       System.out.println("Size of map is:- " + map.size());
       if (map.containsKey("vishal"))
           Integer a = map.get("vishal");
           System.out.println("value for key \"vishal\" is:- " + a);
   public static void print(Map<String, Integer> map)
       if (map.isEmpty())
           System.out.println("map is empty");

map is empty
Size of map is:- 3
{vaibhav=20, vishal=10, sachin=30}
value for key “vishal” is:- 10
map is empty

Read: Java Data Structures

So, this was all about Java Hashmap tutorial. Hope you like our explanation of HashMap in Java.

6. Conclusion: HashMap in Java

Hence, in this Java HashMap Tutorial, we discussed the complete concept of HashMap in Java. Moreover, we saw Java Hashmap example & constructor. Also, we discussed the internal structure of Java HashMap. Still, if any query regarding Hashmap in Java, ask in the comment tab.

See also – 

Java Quiz Part 1 & Part 2

For reference

Did we exceed your expectations?
If Yes, share your valuable feedback on Google

follow dataflair on YouTube

Leave a Reply

Your email address will not be published. Required fields are marked *