Java HashMap
HashMap is a hash table that stores key-value pairs.
HashMap implements the Map interface, stores data based on the hash code of the key, provides fast access, allows at most one null key, and does not support thread synchronization.
HashMap is unordered, meaning it does not record the insertion order.
HashMap extends AbstractMap and implements the Map, Cloneable, and java.io.Serializable interfaces.
The key and value types in HashMap can be the same or different, and can be of type String or Integer.
The elements in HashMap are actually objects. Common primitive types can use their wrapper classes.
The table for primitive types and their corresponding wrapper classes is as follows:
Primitive Type | Reference Type |
---|---|
boolean | Boolean |
byte | Byte |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
char | Character |
The HashMap class is located in the java.util package and needs to be imported before use, with the following syntax:
import java.util.HashMap; // Import the HashMap class
The following example creates a HashMap object named Sites with Integer keys and String values:
HashMap<Integer, String> Sites = new HashMap<Integer, String>();
Adding Elements
HashMap provides many useful methods. The put() method can be used to add key-value pairs:
Example
// Import the HashMap class
import java.util.HashMap;
public class tutorialproTest {
public static void main(String[] args) {
// Create a HashMap object named Sites
HashMap<Integer, String> Sites = new HashMap<Integer, String>();
// Add key-value pairs
Sites.put(1, "Google");
Sites.put(2, "tutorialpro");
Sites.put(3, "Taobao");
Sites.put(4, "Zhihu");
System.out.println(Sites);
}
}
Executing the above code will produce the following output:
{1=Google, 2=tutorialpro, 3=Taobao, 4=Zhihu}
The following example creates a HashMap with String keys and String values:
Example
// Import the HashMap class
import java.util.HashMap;
public class tutorialproTest {
public static void main(String[] args) {
// Create a HashMap object named Sites
HashMap<String, String> Sites = new HashMap<String, String>();
// Add key-value pairs
Sites.put("one", "Google");
Sites.put("two", "tutorialpro");
Sites.put("three", "Taobao");
Sites.put("four", "Zhihu");
System.out.println(Sites);
}
}
Executing the above code will produce the following output:
{four=Zhihu, one=Google, two=tutorialpro, three=Taobao}
Accessing Elements
We can use the get(key) method to retrieve the value corresponding to a key:
Example
// Import the HashMap class
import java.util.HashMap;
public class tutorialproTest {
public static void main(String[] args) {
// Create a HashMap object named Sites
HashMap<String, String> Sites = new HashMap<String, String>();
// Add key-value pairs
Sites.put("one", "Google");
Sites.put("two", "tutorialpro");
Sites.put("three", "Taobao");
Sites.put("four", "Zhihu");
System.out.println(Sites.get("one")); // Output the value for key "one"
}
}
Executing the above code will produce the following output:
Google
public class tutorialproTest {
public static void main(String[] args) {
// Create HashMap object Sites
HashMap<Integer, String> Sites = new HashMap<Integer, String>();
// Add key-value pairs
Sites.put(1, "Google");
Sites.put(2, "tutorialpro");
Sites.put(3, "Taobao");
Sites.put(4, "Zhihu");
System.out.println(Sites.get(3));
}
}
Executing the above code will output the following:
Taobao
Deleting Elements
We can use the remove(key) method to delete the key-value pair corresponding to the key:
Example
// Import HashMap class
import java.util.HashMap;
public class tutorialproTest {
public static void main(String[] args) {
// Create HashMap object Sites
HashMap<Integer, String> Sites = new HashMap<Integer, String>();
// Add key-value pairs
Sites.put(1, "Google");
Sites.put(2, "tutorialpro");
Sites.put(3, "Taobao");
Sites.put(4, "Zhihu");
Sites.remove(4);
System.out.println(Sites);
}
}
Executing the above code will output the following:
{1=Google, 2=tutorialpro, 3=Taobao}
To delete all key-value pairs, you can use the clear method:
Example
// Import HashMap class
import java.util.HashMap;
public class tutorialproTest {
public static void main(String[] args) {
// Create HashMap object Sites
HashMap<Integer, String> Sites = new HashMap<Integer, String>();
// Add key-value pairs
Sites.put(1, "Google");
Sites.put(2, "tutorialpro");
Sites.put(3, "Taobao");
Sites.put(4, "Zhihu");
Sites.clear();
System.out.println(Sites);
}
}
Executing the above code will output the following:
{}
Calculating Size
To calculate the number of elements in the HashMap, you can use the size() method:
Example
// Import HashMap class
import java.util.HashMap;
public class tutorialproTest {
public static void main(String[] args) {
// Create HashMap object Sites
HashMap<Integer, String> Sites = new HashMap<Integer, String>();
// Add key-value pairs
Sites.put(1, "Google");
Sites.put(2, "tutorialpro");
Sites.put(3, "Taobao");
Sites.put(4, "Zhihu");
System.out.println(Sites.size());
}
}
Executing the above code will output the following:
4
Iterating Over HashMap
You can use a for-each loop to iterate over the elements in the HashMap.
If you only want to retrieve the keys, you can use the `keySet()` method, and then you can get the corresponding value using `get(key)`. If you only want to retrieve the values, you can use the `values()` method.
## Example
```java
// Import the HashMap class
import java.util.HashMap;
public class tutorialproTest {
public static void main(String[] args) {
// Create a HashMap object called Sites
HashMap<Integer, String> Sites = new HashMap<Integer, String>();
// Add key-value pairs
Sites.put(1, "Google");
Sites.put(2, "tutorialpro");
Sites.put(3, "Taobao");
Sites.put(4, "Zhihu");
// Output keys and values
for (Integer i : Sites.keySet()) {
System.out.println("key: " + i + " value: " + Sites.get(i));
}
// Return all values
for(String value: Sites.values()) {
// Output each value
System.out.print(value + ", ");
}
}
}
Executing the above code will produce the following output:
key: 1 value: Google
key: 2 value: tutorialpro
key: 3 value: Taobao
key: 4 value: Zhihu
Google, tutorialpro, Taobao, Zhihu,
Java HashMap Methods
Here is a list of common methods for Java HashMap:
Method | Description |
---|---|
clear() | Removes all key-value pairs from the hashMap |
clone() | Clones a hashMap |
isEmpty() | Checks if the hashMap is empty |
size() | Calculates the number of key-value pairs in the hashMap |
put() | Adds a key-value pair to the hashMap |
putAll() | Adds all key-value pairs to the hashMap |
putIfAbsent() | Inserts a key-value pair into the hashMap if the specified key is not already present |
remove() | Removes the mapping for a key from the hashMap if it is present |
containsKey() | Checks if the hashMap contains a mapping for the specified key |
containsValue() | Checks if the hashMap contains a mapping for the specified value |
replace() | Replaces the value for the specified key in the hashMap |
replaceAll() | Replaces all mappings in the hashMap with the result of the given function |
get() | Retrieves the value to which the specified key is mapped |
getOrDefault() | Retrieves the value to which the specified key is mapped, or returns the default value if the key is not found |
forEach() | Performs the specified action for each mapping in the hashMap. |
entrySet() | Returns a Set view of the mappings contained in the hashMap. |
keySet | Returns a Set view of the keys contained in the hashMap. |
values() | Returns a Collection view of the values contained in the hashMap. |
merge() | Adds a key-value pair to the hashMap. |
compute() | Recalculates the value for the specified key in the hashMap. |
computeIfAbsent() | Recalculates the value for the specified key in the hashMap, and adds it if the key is not present. |
computeIfPresent() | Recalculates the value for the specified key in the hashMap, if the key is present. |
For more API methods, see: https://www.tutorialpro.org/manual/jdk11api/java.base/java/util/HashMap.html