Java HashMap Example

The HashMap class is roughly identically tantamount to Hashtable, except that it is unsynchronized and sanctions nulls.Java HashMap class implements the Map interface which sanctions us to store key and value pair, where keys should be unique. If you endeavor to insert the duplicate key, it will supersede the element of the corresponding key. It is facile to perform operations utilizing the key index like the update, delete, etc.


As shown in the above figure, the HashMap class extends AbstractMap class and implements the Map interface, the Cloneable interface, and the Serializable interface.
public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable {


Constructors of Java HashMap class

1) public HashMap(int initialCapacity, float loadFactor)
  Constructs an empty HashMap with the specified initial
capacity and load factor.

2) public HashMap(int initialCapacity)

  Constructs an empty HashMap with the specified initial
capacity and the default load factor (0.75).

3) public HashMap()

  Constructs an empty HashMap with the default initial capacity
(16) and the default load factor (0.75).


4) public HashMap(Map<? extends K, ? extends V> m)

  Constructs a new HashMap with the same mappings as the
specified Map. The HashMap is created with
default load factor (0.75) and an initial capacity sufficient to
hold the mappings in the specified Map.

Important Methods of Java HashMap class

1) public void clear() : 
      Removes all of the mappings from this map.
The map will be empty after this call returns.
2) public boolean isEmpty() :
      Returns true if this map contains no key-value mappings.

3) public Object clone() : 
      Returns a shallow copy of this HashMap instance: the keys and
values themselves are not cloned.

4) public Set<Map.Entry<K,V>> entrySet() :/**
       Returns a  Set view of the mappings contained in this map.

5) public Set<K> keySet() :
       Returns a Set view of the keys contained in this map.
6) public V put(K key, V value) :
       Associates the specified value with the specified key in this map.
If the map previously contained a mapping for the key, the old
value is replaced.
7) public void putAll(Map<? extends K, ? extends V> m):
       Copies all of the mappings from the specified map to this map.
These mappings will replace any mappings that this map had for
any of the keys currently in the specified map.
8) public V putIfAbsent(K key, V value) :
       It inserts the specified value with the specified key in the map only if it 
       is not already specified.

9) public boolean remove(Object key, Object value) : 
       It removes the specified values with the associated specified keys from the map

10) public int size() :
       Returns the number of key-value mappings in this map.

11) public Collection<V> values() :
       Returns a Collection view of the values contained in this map.

12) public boolean replace(K key, V oldValue, V newValue) :
       It replaces the old value with the new value for a specified key.

13) public V replace(K key, V value) :
       It replaces the specified value for a specified key.

14) public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) :
       It 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.replaces the specified value for a specified key. 

15) public final void forEach(Consumer<? super K> action) :
       It performs the given action for each entry in the map until all entries have 
       been processed or the action throws an exception.replaces the specified value 
       for a specified key.

16) public final boolean equals(Object o) :
       It is used to compare the specified Object with the Map.

17) public boolean containsKey(Object key) :
       Returns true if this map contains a mapping for the
specified key.

18) public V get(Object key) : 
       Returns the value to which the specified key is mapped,
or null if this map contains no mapping for the key.

Example:

import java.util.HashMap;
import java.util.Map;
import java.util.Iterator;
import java.util.Set;

public class MapDemo {

public static void main(String args[]) {

/* This is how to declare HashMap */
HashMap<Integer, String> hmap = new HashMap<Integer, String>();

/* Adding elements to HashMap */
hmap.put(1, "Java");
hmap.put(2, "Scala");
hmap.put(7, "Kotlin");
hmap.put(4, "Groovy");
hmap.put(3, "Spark");

/* Display content using Iterator */
Set<?> set = hmap.entrySet();
Iterator<?> iterator = set.iterator();
while (iterator.hasNext()) {
Map.Entry mentry = (Map.Entry) iterator.next();
System.out.print("key is: " + mentry.getKey() + " & Value is: ");
System.out.println(mentry.getValue());
}

/* Get values based on key */
String var = hmap.get(4);
System.out.println("Value at index 4 is: " + var);

/* Remove values based on key */
hmap.remove(3);
System.out.println("Map key and values after removal:");
Set<?> set2 = hmap.entrySet();
Iterator<?> iterator2 = set2.iterator();
while (iterator2.hasNext()) {
Map.Entry mentry2 = (Map.Entry) iterator2.next();
System.out.print("Key is: " + mentry2.getKey() + " & Value is: ");
System.out.println(mentry2.getValue());
}

}
}

Output:

key is: 1 & Value is: Java
key is: 2 & Value is: Scala
key is: 3 & Value is: Spark
key is: 4 & Value is: Groovy
key is: 7 & Value is: Kotlin
Value at index 4 is: Groovy
Map key and values after removal:
Key is: 1 & Value is: Java
Key is: 2 & Value is: Scala
Key is: 4 & Value is: Groovy
Key is: 7 & Value is: Kotlin

More...

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Spring Boot + Mockito simple application with 100% code coverage

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete