In this tutorial, I will present you about the Java HashMap
class and its various operations with the help of examples.
The HashMap
class of the Java collections' framework provides the functionality of the hash table data structure.
It stores elements in key/value
pairs. Here, keys
are unique identifiers used to associate each value
on a map.
The HashMap
class implements the Map
interface.
How to Create a HashMap
In order to create a HashMap, we must import the java.util.HashMap
package first. Once we import the package, here is how we can create HashMaps
in Java.
// hashMap creation with 8 capacity and 0.6 load factor
HashMap<K, V> numbers = new HashMap<>();
In the above code, we have created a hashmap named numbers
. Here, K
represents the key type and V
represents the type of values. For example:
HashMap<String, Integer> numbers = new HashMap<>();
Here, the type of keys is String
and the type of values is Integer.
Example 1: Create HashMap in Java
import java.util.HashMap;
class Main {
public static void main(String[] args) {
// create a hashmap
HashMap<String, Integer> languages = new HashMap<>();
// add elements to hashmap
languages.put("Java", 8);
languages.put("JavaScript", 1);
languages.put("Python", 3);
System.out.println("HashMap: " + languages);
}
}
Output
HashMap: {Java=8, JavaScript=1, Python=3}
Top comments (0)