What is java hashmap: Lean Hashmap Java in full details

Java hashmap | What is java hashmap?

What is java hashmap?

 

HashMap stores the data in (Key, Value) pairs. The basic implementation of the Map interface of Java provided by the hashMap. Since Java 1.2 HashMap is a part of Java’s collection.

If you want to access its value then you have to remember its key. It uses a technique called Hashing for it’s known as HashMap.

Using the Hashing technique we can convert a large String to small String that represents the same String. A shorter value helps us for faster searches and indexing.

Internally HashSet also uses HashMap. Internally it uses a link list to store key-value pairs already explained in HashSet in detail.

HashMap Few important features:

  • HashMap it’s an important part of the java.util package.
  • The HashMap extends an abstract class AbstractMap basically which also provides an incomplete implementation of Map interface.
  • It also implements Serializable and Cloneable interface.
  • HashMap allows duplicate values but it doesn’t allow duplicate keys. That means more than 1 key can contain a single value but A single key cannot contain more than 1 value.
  • HashMap also allows null keys but only once and multiple null values.
  • This class makes no ensures as to the order of the map; in particular, it does no longer assure that the order will remain constant through the time. It is much like HashTable but is unsynchronized.

Features of Java Hashmap:

a) By forming a key-value pair the values can be stored on the map. Using the help of the key the value can be retrieved by passing it to the correct method.

b) It will throw a ‘NoSuchElementException’ if there is no element that exists on the map.

c) A  HashMap only stores object references. so, it is impossible to use primitive data types like double or int. We use wrapper class (like Double or Integer) instead.

Features of Java Hashmap | What is java hashmap

Synchronized HashMap:

HashMap is unsynchronized As it is told that, i.e. multiple threads can simultaneously access it. It is necessary to make it synchronized externally if multiple threads access this class simultaneously and at least one thread manipulates it structurally. Actually it is done through synchronizing some object which encapsulates the map. It can be wrapped around the Collections if there is no such object exists. With the help of synchronized map() to accidental unsynchronized access and make HashMap synchronized. The following example blew:

Map mp = Collections.synchronizedMap(new HashMap(...));

Now the Map mp is synchronized.

This class iterators are fail-fast if any structure modification is achieved after the creation of iterator, in any way to except through the iterator’s remove method. It will be throwing the ConcurrentModificationException in the failure of the iterator.

Hashmap Performance java:

Basically, the  HashMap performance depends on 2 parameters:

  1. The Initial Capacity and
  2. The Load Factor

Capacity is simply the number of buckets as we already said whereas the Initial Capacity is the capacity of HashMap instance when it is created.

When the rehashing should be done the Load Factor is a measure that. A process of increasing the capacity is also known as rehashing.

Actually the HashMap capacity is multiplied by 2. The fraction of the HashMap is allowed to fill before rehashing the Load Factor is also a measure that.

The capacity is increased that is rehashing is done when the number of entries in HashMap increases the product of the current capacity and load factor.

The rehashing will never be done if the initial capacity is kept higher. but it increases by iteration time complexity by keeping it higher.

To increase its performance it should be chosen very cleverly. To set the initial capacity the expected number of values should be taken into account.

Actually the most usually preferred load factor value is 0.75 which provides a good deal among time and space costs. Actually, the load factor’s value varies among 0 and 1.

Constructors in Java HashMap:

Actually the HashMap provides us 4 constructors and access modifier of each is public:

  1. HashMap(): It creates an instance of HashMap with initial capacity 16 and load factor 0.75 actually it is a default constructor.
  2. HashMap(int initial capacity): With specified initial capacity and load factor 0.75 it creates a HashMap instance.
  3. HashMap(int initial capacity, float loadFactor): With specified initial capacity and specified load factor it creates a HashMap instance.
  4. HashMap(Map map): With the same mappings as a specified map it actually creates an instance of HashMap.

Example:

// Using Java program to illustrate
// Java.util.HashMap
 
import java.util.HashMap;
import java.util.Map;
 
public class Example {
    public static void main(String[] args)
    {
 
        HashMap<String, Integer> map
            = new HashMap<>();
 
        print(map);
        map.put("Andrew", 20);
        map.put("Jhon", 32);
        map.put("Thomas", 25);
 
        System.out.println("Size of map is:- "
                           + map.size());
 
        print(map);
        if (map.containsKey("Andrew")) {
            Integer a = map.get("Andrew");
            System.out.println("value for key"
                               + " \"Andrew\" is:- "
                               + a);
        }
 
        map.clear();
        print(map);
    }
 
    public static void print(Map<String, Integer> map)
    {
        if (map.isEmpty()) {
            System.out.println("map is empty");
        }
 
        else {
            System.out.println(map);
        }
    }
}
Output:
map is empty
Size of map is:- 3
{Thomas=25, Andrew=20, Jhon=32}
value for key "Andrew" is:- 20
map is empty

The time complexity of java HashMap:

For basic operations, HashMap provides a constant time complexity, get and put it if the hash function is properly written and it disperses the elements properly among the buckets.

Iteration over HashMap depends on the capacity of the HashMap and a number of key-value pairs. Basically, it is directly proportional to the capacity + size.

In HashMap capacity is the number of buckets. initially, to keep a high number of buckets in HashMap is not a good idea.

Methods of Java HashMap class:

Method Description
void clear() The void clear() method is used to remove all of the mappings from this map.
boolean isEmpty() If this map contains no key-value mappings then it is used to return true.
Object clone() To return a shallow copy of this HashMap instance, the Object clone() method has used. The keys and values themselves are not cloned.
Set entrySet() The Set entrySet() method is used to return a collection view of the mappings contained in this map.
Set keySet() The Set keySet() method is used to return a set view of the keys contained in this map.
V put(Object key, Object value) To insert an entry in the map this V put(Object key, Object value) method is used.
void putAll(Map map) The void putAll(Map map) method is used to insert the specified map in the map.
V putIfAbsent(K key, V value) the ‘V putIfAbsent(K key, V value)’ method is used for inserts the specified value with the specified key in the map only if it is not already specified.
V remove(Object key) The V remove(Object key) method is used to delete an entry for the specified key.
boolean remove(Object key, Object value) It removes the specified values with the associated specified keys from the map.
V compute(K key, BiFunction<? super K,? super V,? extends V> remappingFunction) To compute a mapping for the specified key and its current mapped value (or null if there is no current mapping) this method is used.
V computeIfAbsent(K key, Function<? super K,? extends V> mappingFunction) V computeIfAbsent(K key, Function<? super K,? extends V> mappingFunction) is used to compute its value using the given mapping function, if the specified key is not already associated with a value (or is mapped to null), and enters it into this map unless null.
V computeIfPresent(K key, BiFunction<? super K,? super V,? extends V> remappingFunction) This method is used to compute a new mapping given the key and its current mapped value if the value for the specified key is present and non-null.
boolean containsValue(Object value) The boolean containsValue(Object value) method is returns true if some value equal to the value exists within the map, else return false.
boolean containsKey(Object key) The boolean containsKey(Object key) method is returns true if some key equal to the key exists within the map, else return false.
boolean equals(Object o) The boolean equals(Object o) is used to compare the specified Object with the Map.
void forEach(BiConsumer<? super K,? super V> action) The void forEach(BiConsumer<? super K,? super V> action) is performs the given action for each entry in the map until all entries have been processed or the action throws an exception.
V get(Object key) The V get(Object key method is returns the object that contains the value associated with the key.
V getOrDefault(Object key, V defaultValue) The V getOrDefault(Object key, V defaultValue) method returns the value to which the specified key is mapped, or defaultValue if the map contains no mapping for the key.
boolean isEmpty() This boolean isEmpty() method returns true if the map is empty; returns false if it contains at least one key.
V merge(K key, V value, BiFunction<? super V,? super V,? extends V> remappingFunction) It is used If the specified key is not already associated with a value or is associated with null, associates it with the given non-null value.
V replace(K key, V value) V replace(K key, V value) method is used to replaces the specified value for a specified key.
boolean replace(K key, V oldValue, V newValue) The boolean replace(K key, V oldValue, V newValue) method is used to replaces the old value with the new value for a specified key.
void replaceAll(BiFunction<? super K,? super V,? extends V> function) This method is used replaces each entry’s value with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception.
Collection<V> values() Collection<V> values() is used to returns a collection view of the values contained in the map.
int size() The int size() method used to returns the number of entries in the map.

Java HashMap example to add() elements

Different ways to insert elements in HashMap:

import java.util.*;
class HashMapExp{
public static void main(String args[]){
   HasHmpap<Integer,String> Hmpp=new HashMap<Integer,String>();
    System.out.println("Primary list of elements: "+Hmp);
      Hmp.put(111,"Andrew");
      Hmp.put(112,"Thomas");
      Hmp.put(113,"Linda");
      System.out.println("After put() method invoking ");
      for(Map.Entry m:Hmp.entrySet()){
        System.out.println(m.getKey()+" "+m.getValue());
      }
      Hmp.putIfAbsent(114, "Monika");
      System.out.println("After putIfAbsent() method invoking ");
      for(Map.Entry m:Hmp.entrySet()){
          System.out.println(m.getKey()+" "+m.getValue());
      }
      HashMap<Integer,String> map=new HashMap<Integer,String>();
      map.put(115,"Jonny");
      map.putAll(Hmp);
      System.out.println("After invoking putAll() method ");
      for(Map.Entry m:map.entrySet()){
           System.out.println(m.getKey()+" "+m.getValue());
      }
 }
}

Output:

Primary list of elements: {}
After put() method invoking
111 Andrew
112 Thomas
113 Linda
After putIfAbsent() method invoking  
111 Andrew
112 Thomas
113 Linda
114 Monika
After putAll() method invoking  
111 Andrew
112 Thomas
113 Linda
114 Monika
115 Jonny

Java HashMap example to remove() elements

import java.util.*;
public class HashMapExp2 {
   public static void main(String args[]) {
    HashMap<Integer,String> Hmp=new HashMap<Integer,String>();
      Hmp.put(111,"Andrew");
      Hmp.put(112,"Thomas");
      Hmp.put(113,"Linda");
      Hmp.put(114,"Monika");
    System.out.println("Primary list of elements: "+Hmp);
    //key-based removal
    Hmp.remove(111);
    System.out.println("This is updated list of elements: "+Hmp);
    //value-based removal
    Hmp.remove(112);
    System.out.println("This is updated list of elements: "+Hmp);
    //key-value pair based removal
    Hmp.remove(113, "Linda");
    System.out.println("This is updated list of elements: "+Hmp);
   }
}

Output:

Primary list of elements: {111=Andrew, 112=Thomas, 113=Linda, 114=Monika}
Updated list of elements: {112=Thomas, 113=Linda, 114=Monika}
Updated list of elements: {113=Linda, 114=Monika}
Updated list of elements: {114=Monika}

Java HashMap example to replace() elements

import java.util.*;
class HashMapExp3{
 public static void main(String args[]){
   HashMap<Integer,String> Hmp=new HashMap<Integer,String>();
      Hmp.put(111,"Andrew");
      Hmp.put(112,"Thomas");
      Hmp.put(113,"Linda");
      System.out.println("Primary list of elements:");
     for(Map.Entry m:Hmp.entrySet())
     {
        System.out.println(m.getKey()+" "+m.getValue());
     }
     System.out.println("Updated list of elements:");
     Hmp.replace(113, "Monika");
     for(Map.Entry m:Hmp.entrySet())
     {
        System.out.println(m.getKey()+" "+m.getValue());
     }
     System.out.println("Updated list of elements:");
     Hmp.replace(112, "Thomas", "Jonny");
     for(Map.Entry m:Hmp.entrySet())
     {
        System.out.println(m.getKey()+" "+m.getValue());
     }
     System.out.println("Updated list of elements:");
     Hmp.replaceAll((k,v) -> "Eleonora");
     for(Map.Entry m:Hmp.entrySet())
     {
        System.out.println(m.getKey()+" "+m.getValue());
     }
 }
}
Initial list of elements:
111 Andrew
112 Thomas
113 Linda
The updated list of elements:
111 Andrew
112 Thomas
103 Monika
The updated list of elements:
111 Andrew
112 Jonny
103 Monika
The updated list of elements:
100 Eleonora
101 Eleonora
102 Eleonora
Close