English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
New features
In this tutorial, we will learn about the Java HashMap class and its methods with the help of examples.The HashMap class provided by the Java Collection FrameworkMap interface
Create a HashMap
//To create a HashMap, we must first import the java.util.HashMap package. After importing the package, we can use Java to create a hash table.8a capacity and 0.6The HashMap of load factors HashMap<Key, Value> numbers = new HashMap<>();8, 0.6f);
In the above code, we created a HashMap named numbers.
Here,
Key -A unique identifier used to associate each element (value) in the map
Value -The element associated with the key in the map
Please note new HashMap<>(8,0.6). Here, the first parameter is capacity, and the second parameter is loadFactor.
capacity - The capacity of HashMap is8. This means that it can store8entries.
loadFactor - The load factor of hashmap is 0.6. This means that every time the hash table is filled60% of the entries will be moved to a new hash table, whose size is twice the size of the original hash table.
Default capacity and load factor
It is allowed to create a hash table without defining its capacity and load factor. For example,
//With default capacity and load factor HashMap HashMap<Key, Value> numbers1 = new HashMap<>();
By default,
The capacity of HashMap will be 16
The load factor will be 0.75
This is how we create a HashMap that contains all elements of other maps.
import java.util.HashMap; class Main { public static void main(String[] args) { //Create a hashmap of even numbers HashMap<String, Integer> evenNumbers = new HashMap<>(); evenNumbers.put("Two", 2); evenNumbers.put("Four", 4); System.out.println("HashMap1: " + evenNumbers); //Create a HashMap from another hashmap HashMap<String, Integer> numbers = new HashMap<>(evenNumbers); numbers.put("Three", 3); System.out.println("HashMap2: " + numbers); } }
Output Result
HashMap1: {Four=4, Two=2} HashMap2: {Two=2, Three=3, Four=4}
This HashMap class provides various methods, allowing us to perform various operations on the map.
put() - Insert the specified key/Value mapping is inserted into the map
putAll() - Insert all entries from the specified map into this map
putIfAbsent() - If the specified key does not exist in the map, then insert the specified key/Value mapping is inserted into the map
For example,
import java.util.HashMap; class Main { public static void main(String[] args) { //Creating even number HashMap HashMap<String, Integer> evenNumbers = new HashMap<>(); // Using put() evenNumbers.put("Two", 2); evenNumbers.put("Four", 4); // Using putIfAbsent() evenNumbers.putIfAbsent("Six", 6); System.out.println("Even number HashMap: " + evenNumbers); //Creating HashMap of numbers HashMap<String, Integer> numbers = new HashMap<>(); numbers.put("One", 1); // Using putAll() numbers.putAll(evenNumbers); System.out.println("numbers的HashMap: "} + numbers); } }
Output Result
偶数HashMap: {Six=6, Four=4, Two=2} numbers的HashMap: {Six=6, One=1, Four=4, Two=2}
1.使用entrySet(),keySet()和values()
entrySet() -返回一组所有键/值映射的map
keySet() -返回map所有键的集合
values() -返回map所有值的集合
For example,
import java.util.HashMap; class Main { public static void main(String[] args) { HashMap<String, Integer> numbers = new HashMap<>(); numbers.put("One", 1); numbers.put("Two", 2); numbers.put("Three", 3); System.out.println("HashMap: "); + numbers); // 使用 entrySet() System.out.println("Key/Value 映射: " + numbers.entrySet()); // 使用 keySet() System.out.println("Keys: " + numbers.keySet()); // 使用 values() System.out.println("Values: " + numbers.values()); } }
Output Result
HashMap: {One=1, Two=2, Three=3} Key/Value 映射: [One=1, Two=2, Three=3] Keys: [One, Two, Three] Values: [1, 2, 3]
2.使用get()和getOrDefault()
get() - 返回与指定键关联的值。如果找不到键,则返回null。
getOrDefault() - 返回与指定键关联的值。如果找不到键,则返回指定的默认值。
For example,
import java.util.HashMap; class Main { public static void main(String[] args) { HashMap<String, Integer> numbers = new HashMap<>(); numbers.put("One", 1); numbers.put("Two", 2); numbers.put("Three", 3); System.out.println("HashMap: "); + numbers); // 使用 get() int value1 = numbers.get("Three"); System.out.println("返回数字: " + value1); // 使用 getOrDefault() int value2 = numbers.getOrDefault("Five", 5); System.out.println("返回数字: " + value2); } }
Output Result
HashMap: {One=1, Two=2, Three=3} 返回数字: 3 返回数字: 5
remove(key) - 返回并从映射中删除与指定键相关联的项
remove(key, value) - 仅当指定键映射到指定值并返回布尔值时,才从映射中删除该项
For example,
import java.util.HashMap; class Main { public static void main(String[] args) { HashMap<String, Integer> numbers = new HashMap<>(); numbers.put("One", 1); numbers.put("Two", 2); numbers.put("Three", 3); System.out.println("HashMap: "); + numbers); //单个参数的删除方法 int value = numbers.remove("Two"); System.out.println("删除值: " + value); //具有两个参数的删除方法 boolean result = numbers.remove("Three", 3); System.out.println("条目"3Was it deleted? " + result); System.out.println("Updated HashMap: ") + numbers); } }
Output Result
HashMap: {One=1, Two=2, Three=3} Delete value: 2 Entry3Was it deleted? True Updated HashMap: {One=1}
replace(key, value) - Replace the value of key with value
replace(key, old, new) - Only replace the old value with the new value when the old value is already associated with the specified key key
replaceAll(function) - Replace each mapped value with the result of the specified function
For example,
import java.util.HashMap; class Main { public static void main(String[] args) { HashMap<String, Integer> numbers = new HashMap<>(); numbers.put("First", 1); numbers.put("Second", 2); numbers.put("Third", 3); System.out.println("Original HashMap: ") + numbers); // Use replace() numbers.replace("Second", 22); numbers.replace("Third", 3, 33); System.out.println("Use replace to replace the value of HashMap: ") + numbers); // Use replaceAll() numbers.replaceAll((key, oldValue) -> oldValue + 2); System.out.println("Use replaceAll to replace the value of HashMap: ") + numbers); } }
Output Result
Original HashMap: {Second=2, Third=3, First=1} Use replace to replace the value of HashMap: {Second=22, Third=33, First=1} Use replaceAll to replace the value of HashMap: {Second=24, Third=35, First=3}
In the above program, note the statement
numbers.replaceAll((key, oldValue) -> oldValue + 2);
Here, this method accesses all entries in the map. Then, it replaces all values withlambda expressionThe new value provided.
1.Use compute() method
compute() - Use the specified function to calculate a new value. Then, the calculated value will be associated with the specified key.
computeIfAbsent() - If the specified key is not mapped to any value, this method will use the specified function to calculate a new value. Then, the new value will be associated with the key.
computeIfPresent() -If the specified key is already mapped to any value, this method will use the specified function to calculate a new value. Then, the new value will be associated with the key.
For example,
import java.util.HashMap; class Main { public static void main(String[] args) { HashMap<String, Integer> numbers = new HashMap<>(); numbers.put("First", 1); numbers.put("Second", 2); System.out.println("original HashMap: " + numbers); // Use compute() numbers.compute("First", (key, oldValue) -> oldValue + 2); numbers.compute("Second", (key, oldValue) -> oldValue + 1); System.out.println("HashMap use compute(): ") + numbers); // using computeIfAbsent() numbers.computeIfAbsent("Three", key -> 5); System.out.println("HashMap using computeIfAbsent(): " + numbers); // using computeIfPresent() numbers.computeIfPresent("Second", (key, oldValue) -> oldValue * 2); System.out.println("HashMap using computeIfPresent(): " + numbers); } }
Output Result
original HashMap: {Second=2, First=1} HashMap using compute(): {Second=3, First=3} HashMap using computeIfAbsent(): {Second=3 First=3, Three=5} HashMap using computeIfPresent(): {Second=6, First=3, three=5}
In the above example, we use the compute() method to recalculate the value of the map.
Here, we uselambda expressionas a method parameter to recalculate the value.
2.Using merge() method
If the specified key is not associated, the merge() method will associate the specified value with the specified key.
However, if the specified key is already associated with a value, it will merge the new specified value with the existing old value. For example
import java.util.HashMap; class Main { public static void main(String[] args) { HashMap<String, Integer> numbers = new HashMap<>(); numbers.put("First", 1); numbers.put("Second", 2); System.out.println("original HashMap: " + numbers); // using the merge() method numbers.merge("First", 4, (oldValue, newValue) -> oldValue + newValue); System.out.println("new HashMap: " + numbers); } }
Output Result
original HashMap: {Second=2, First=1} new HashMap: {Second=2, First=5}
In the above example, the merge() method takes3with parameters:key,newValueand a lambda expression (used to calculate the new merged value).
Method | Description |
---|---|
clear() | Remove all entries from the map |
containsKey() | Check if the map contains the specified key and return a boolean value |
containsValue() | Check if the map contains the specified value and return a boolean value |
size() | Return the size of the map |
isEmpty() | Check if the map is empty and return a boolean value |
In the HashMap, we can
Traverse them Keys
Traverse them Values
Traverse them Keys/Values
1.Using forEach loop
import java.util.HashMap; import java.util.Map.Entry; class Main { public static void main(String[] args) { //Create HashMap HashMap<String, Integer> numbers = new HashMap<>(); numbers.put("One", 1); numbers.put("Two", 2); numbers.put("Three", 3); System.out.println("HashMap: "); + numbers); //Access the key/value (key/value pair System.out.print("Item: "); for(Entry<String, Integer> entry: numbers.entrySet()) { System.out.print(entry); System.out.print(", "); } //Access key System.out.print("\nAll Keys: "); for(String key: numbers.keySet()) { System.out.print(key); System.out.print(", "); } //Access value System.out.print("\nAll Values: "); for(Integer value: numbers.values()) { System.out.print(value); System.out.print(", "); } } }
Output Result
HashMap: {One=1, Two=2, Three=3} All Entries: One=1, Two=2, Three=3 All Keys: One, Two, Three, All Values: 1, 2, ,3,
In the above program, please note that we have imported the java.util.Map.Entry package. Here, Map.Entry is a nested class of the Map interface.
This nested class returns a view (elements) of the map.
2.Using iterator() method
You can also use the iterator() method to iterate over a HashMap. To use this method, we must import the java.util.Iterator package.
import java.util.HashMap; import java.util.Iterator; import java.util.Map.Entry; class Main { public static void main(String[] args) { //Create HashMap HashMap<String, Integer> numbers = new HashMap<>(); numbers.put("One", 1); numbers.put("Two", 2); numbers.put("Three", 3); System.out.println("HashMap: "); + numbers); //Create an Iterator object Iterator<Entry<String, Integer>> iterate1 = numbers.entrySet().iterator(); // Access Key/Value pair System.out.print("All entries: "); while(iterate1.hasNext()) { System.out.print(iterate1.next()); System.out.print(", "); } // Access key Iterator<String> iterate2 = numbers.keySet().iterator(); System.out.print("\nAll Keys: "); while(iterate2.hasNext()) { System.out.print(iterate2.next()); System.out.print(", "); } // Access value Iterator<Integer> iterate3 = numbers.values().iterator(); System.out.print("\nAll Values: "); while(iterate3.hasNext()) { System.out.print(iterate3.next()); System.out.print(", "); } } }
Output Result
HashMap: {One=1, Two=2, Three=3} All Entries: One=1, Two=2, Three=3 All Keys: One, Two, Three, All Values: 1, 2, 3,
In the above program, please note that we have imported the java.util.Map.Entry package. Here Map.Entry is a nested class of the Map interface.
This nested class returns a view (elements) of the map.