The use of HashMap in java projects and small cases

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:

  1. Import the HashMap class:import java.util.HashMap;
  2. Create a HashMap object:HashMap<KeyType, ValueType> map = new HashMap<>();
  3. Insert key-value pairs into HashMap:map.put(key, value);
  4. Get value by key:ValueType value = map.get(key);
  5. Determine whether the HashMap contains the specified key:boolean containsKey = map.containsKey(key);
  6. Delete the specified key-value pair:map.remove(key);
  7. Get the key set in HashMap:Set<KeyType> keySet = map.keySet();
  8. Get the value collection in HashMap:Collection<ValueType> values = map.values();
  9. Traverse the key-value pairs in the HashMap:

    Copy

    for (KeyType key : map.keySet()) {
        ValueType value = map.get(key);
        // 进行操作
    }
    
  10. Get the size of the HashMap (the number of key-value pairs):int size = map.size();
  11. 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.

Guess you like

Origin blog.csdn.net/qq_60870118/article/details/132189579