HashMap is one of the most commonly used data structures in Java. It is implemented based on a hash table and has good performance in insertion and lookup.
How to use HashMap:
- Import the HashMap class:
import java.util.HashMap;
- Create a HashMap object:
HashMap<KeyType, ValueType> map = new HashMap<>();
- Insert key-value pairs into HashMap:
map.put(key, value);
- Get value by key:
ValueType value = map.get(key);
- Determine whether the HashMap contains the specified key:
boolean containsKey = map.containsKey(key);
- Delete the specified key-value pair:
map.remove(key);
- Get the key set in HashMap:
Set<KeyType> keySet = map.keySet();
- Get the value collection in HashMap:
Collection<ValueType> values = map.values();
- Traverse the key-value pairs in the HashMap:
Copy
for (KeyType key : map.keySet()) { ValueType value = map.get(key); // 进行操作 }
- Get the size of the HashMap (the number of key-value pairs):
int size = map.size();
- Clear all key-value pairs in HashMap:
map.clear();
HashMap case example:
Copy
import java.util.HashMap;
public class HashMapExample {
public static void main(String[] args) {
HashMap<String, Integer> grades = new HashMap<>();
// 添加学生的成绩
grades.put("Alice", 85);
grades.put("Bob", 90);
grades.put("Charlie", 75);
// 获取指定学生的成绩
int aliceGrade = grades.get("Alice");
System.out.println("Alice's grade: " + aliceGrade);
// 判断是否包含指定学生
boolean containsBob = grades.containsKey("Bob");
System.out.println("Contains Bob: " + containsBob);
// 删除指定学生的成绩
grades.remove("Charlie");
System.out.println("Size of grades: " + grades.size());
// 遍历所有学生的成绩
for (String student : grades.keySet()) {
int grade = grades.get(student);
System.out.println(student + "'s grade: " + grade);
}
// 清空所有学生的成绩
grades.clear();
System.out.println("Size of grades after clear: " + grades.size());
}
}
This example demonstrates how to use HashMap to store students' grades, and perform operations such as obtaining, deleting, determining whether it is included, traversing, and clearing.