What is a hashmap Java

HashMap Java class implements the Map interface that permits us to keep key and value pairs in which keys must be distinct. If you attempt to add an identical key in the same key field, it replaces that element with the original key. It is easy to perform actions using keys like indexes, deletion, updating, etc. The class HashMap is part of java.util package.

HashMap within Java is similar to the older Hashtable class, however, it’s not synced. It is able to store null elements as well, however, there must be just one key that is null. As of Java 5, it is known as HashMap in which K is for key and V stands for value. It inherits from the AbstractMap class, and it is able to implement its Map interface.

HashMap is part of Java’s collection as of Java 1.2. This class is part of java.utilpackage. It is the base application of the Map interface in Java. It stores information in (Key Value) pairs. You can access them via an index of another kind (e.g. an Integer). One object can be used as an index (index) in relation to another (value). If you attempt to add an identical key into the index, this will substitute that element in the key.

HashMap can be like HashTable However, it’s unsynchronized. It can store null keys, too but there is just one key that is null, and there could be an unlimited number of null values. This class is not able to provide any assurances about the order in which you will receive the map. For this class to be used as well as its techniques, you have to install the java.util.HashMap package or its superclass.

Tips to be remembered

  • HashMap Java contains values based on the key.
  • HashMap Java contains only unique keys.
  • HashMap Java may have one null key and may have several null values.
  • HashMap Java is non-synchronized.
  • HashMap Java maintains no order.
  • The initial capacity of the Java HashMap class is 16 with an initial load factor of 0.75.

The hierarchy of the HashMap class

As illustrated in the preceding illustration, the HashMap class extends AbstractMap class and implements the Map interface.

HashMap class declaration

Let’s review the declaration of the java.util.HashMap class.

public class HashMap<K,V> extends AbstractMap<K,V>
                          implements Map<K,V>, Cloneable, Serializable

Parameters for the class HashMap

Let’s examine the parameters of the java.util.HashMap class.

  • K It is the kind of keys that is maintained in this map.
  • V It’s the kind of the mapped value.

Constructors of the Java HashMap class

Constructor Description
HashMap() It is used to create an initial HashMap.
HashMap(Map m) This is utilized to create the hash map, using the elements from the Map object, m.
HashMap(int capacity) The function is set the capacities of the hashmap to the integer number specified capacity.
HashMap(int capacity, loadFactor float) It’s used to set the capacity as well as the loading factor for the map through its arguments.

Techniques for Java HashMap class

Method Description
void clear() It’s used to erase all mappings from the map.
A boolean expression is empty() It will return true if this map has any key-value maps.
Cloning an object() It’s used to return an unintentional replica that is a shallow copy of the HashMap instance. The values and keys themselves are not copied.
Set entrySet() It’s used to provide an overview of the mappings that are contained within this map.
KeySetSet() It’s used to return an outline view of the keys inside this map.
V put(Object key, Object value) It’s used to add an entry into the map.
void putAll(Map map) It’s used to place the map you want to insert into the map.
V putIfAbsent(K key, V value) It adds the specified value by using the key you specify into the mapping only when the key is not already present in the map.
Remove (Object key) remove(Object key) It is used to remove an entry for the specific key.
boolean remove(Object key, Object value) It erases the specified values and the associated keys out of the mapping.
V compute(K key, BiFunction remappingFunction) It’s used to calculate the mapping of the key and the current value it is mapped to (or null if there’s no mapping currently).
V computeIfAbsent(K key, Function mappingFunction) It computes its value by using the mapping function, in the event that the key you specify isn’t already associated with an amount (or is assigned to null) and it then enters it into this map , unless it is it is null.
V computeIfPresent(K key, BiFunction remappingFunction) It’s used to calculate an entirely new mapping using the key’s value and the current value, in the event that the value of the key specified is present and is not null.
boolean containsValue(Object value) This method will return the value if a value that is equal to the value is present within the map. If not, it will it returns false.
Boolean containsKey(Object key) This method is true if a key which is similar to the key is present within the map. If not, it returns false.
boolean equals(Object o) It’s used to compare the Object being studied against the Map.
Void forEach(BiConsumer action) It executes the action for each entry on the database until all entries are processed or it throws an error.
V get(Object key) This method returns an object that holds the value that is associated with the key.
V getOrDefault(Object key, V defaultValue) The return value is the one to which the key is mapped or defaultValue in the event that the map has no maps for this key.
Boolean isEmpty() This method is true if the map is empty. It returns false if the map contains at most one key.
V merge(K key, V value, BiFunction remappingFunction) If the key you are looking for does not already have an existing value or with null, then it will be associated with the non-null value given.
V replace(K key, V value) It substitutes the value for a given key.
boolean replace(K key, V oldValue, V newValue) It replaces the previous value by a new value for the key you have specified.
void replaceAll(BiFunction function) It alters the value of each entry through the process of calling the function that was specified for each record until the entire entries are processed or the function throws an exception.
Values of collection() It displays a summary view of the data included on the map.
Int size() This method calculates the total number of entries in the map.

 HashMap Java Example

Let’s see a simple example of HashMap to store key and value pairs.

import java.util.HashMap;
public class ABCD {

public static void main(String[] args)
{

HashMap<String, Integer> map = new HashMap<>();

map.put("Android", 10);
map.put("Apple", 20);
map.put("Window", 30);

System.out.println("Size of map is:- "
+ map.size());

System.out.println(map);

// Checking if a key is present and if
// present, print value by passing
// random element
if (map.containsKey("Apple")) {

// Mapping
Integer a = map.get("Apple");

// Printing value for the corresponding key
System.out.println("value for key"
+ " \"Apple\" is:- " + a);
}
}
}

Output
Size of map is:- 3
{Android=10, Apple=20, Window=30}
value for key "Apple" is:- 20

 

hashmap vs hashtable

HashMap and Hashtable stores the key and value pairs within Hash tables. When you use HashTable or Hashtable or HashMap we define an object to be utilized as a key as well as the value you want to associate with the key. Keys are then washed and the hash code that is generated is used as an index where the value is stored in the table. Let’s discuss the issue with reference to an example.

Hashmap vs Hashtable

  • HashMap is not synchronized. It’s not thread-safe, and is not able to be shared between multiple threads without proper synchronization code . Hashtable is synced. It’s thread-safe and it can be shared among multiple threads.
  • HashMap permits one null key with multiple value null, whereas Hashtable does not permit any null value or key.
  • HashMap is usually preferred over HashTable when thread synchronization isn’t required.

Difference Between Hashmap and Hashtable

S. No. Hashmap Hashtable
1. There is no method that is synchronized. Each method is coordinated.
2. Multiple threads may be operating simultaneously and thus hashmap’s object isn’t thread-safe. At any given time, only one thread is permitted to run the Hashtable’s object. This makes it secure for threads.
3. Threads do not have to wait, and thus the performance is very high. This increases the time spent waiting of the thread and , consequently, the performance decreases.
4. Null is permitted in both value and key. Null isn’t allowed for key and value. If we do, we’ll get an error indicating that null is not allowed.
5. It’s made available with version 1.2. 1.2 version. It was introduced in the 1.0 version.
6. It’s not considered to be a tradition. It’s a legacy.

 

Read More:-

 

You may also like...