Java HashMap案例如何存取值

wen java案例 27

Java HashMap存取值案例

基础存取值操作

import java.util.HashMap;
import java.util.Map;
public class HashMapExample {
    public static void main(String[] args) {
        // 1. 创建HashMap
        Map<String, Integer> scores = new HashMap<>();
        // 2. 存储数据(put)
        scores.put("张三", 95);
        scores.put("李四", 88);
        scores.put("王五", 92);
        scores.put("张三", 98); // key已存在,会覆盖旧值
        // 3. 获取数据(get)
        Integer score = scores.get("张三");  // 98
        System.out.println("张三的成绩:" + score);
        // 4. 获取不存在的数据
        Integer nullScore = scores.get("赵六");  // null
        System.out.println("赵六的成绩:" + nullScore);
        // 5. 使用getOrDefault避免null
        Integer defaultScore = scores.getOrDefault("赵六", 0);
        System.out.println("赵六的成绩(默认值):" + defaultScore);
    }
}

完整的增删改查案例

import java.util.HashMap;
import java.util.Map;
public class HashMapCompleteExample {
    public static void main(String[] args) {
        // 创建商品库存管理Map
        Map<String, Integer> inventory = new HashMap<>();
        // ========== 增(Create) ==========
        System.out.println("=== 添加商品 ===");
        inventory.put("iPhone 15", 100);
        inventory.put("MacBook Pro", 50);
        inventory.put("AirPods", 200);
        // 使用putIfAbsent:只有当key不存在时才添加
        inventory.putIfAbsent("iPad", 80);
        inventory.putIfAbsent("iPhone 15", 500); // key已存在,不生效
        System.out.println("库存:" + inventory);
        // ========== 查(Read) ==========
        System.out.println("\n=== 查询商品 ===");
        // 方式1:直接get
        Integer iphoneCount = inventory.get("iPhone 15");
        System.out.println("iPhone 15数量:" + iphoneCount);
        // 方式2:存在性检查
        if (inventory.containsKey("MacBook Pro")) {
            System.out.println("MacBook Pro存在,数量:" + inventory.get("MacBook Pro"));
        }
        // 方式3:批量查询
        inventory.forEach((product, count) -> {
            System.out.println(product + ": " + count + "台");
        });
        // ========== 改(Update) ==========
        System.out.println("\n=== 更新商品 ===");
        // 方式1:直接替换
        inventory.put("iPhone 15", 80);  // 直接覆盖
        System.out.println("iPhone 15更新后:" + inventory.get("iPhone 15"));
        // 方式2:替换指定值
        inventory.replace("AirPods", 150);  // 只替换存在的key
        System.out.println("AirPods替换后:" + inventory.get("AirPods"));
        // 方式3:条件替换(旧值匹配才替换)
        boolean replaced = inventory.replace("MacBook Pro", 50, 30);
        System.out.println("MacBook Pro条件替换结果:" + replaced + 
                         ",当前数量:" + inventory.get("MacBook Pro"));
        // ========== 删(Delete) ==========
        System.out.println("\n=== 删除商品 ===");
        // 方式1:直接删除
        inventory.remove("iPad");
        System.out.println("删除iPad后:" + inventory);
        // 方式2:条件删除(key和value都匹配)
        boolean removed = inventory.remove("AirPods", 150);
        System.out.println("条件删除结果:" + removed + ",当前库存:" + inventory);
        // 方式3:清空所有
        // inventory.clear();  // 谨慎使用
    }
}

实用操作技巧

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class HashMapAdvancedExample {
    public static void main(String[] args) {
        Map<String, String> map = new HashMap<>();
        map.put("key1", "value1");
        map.put("key2", "value2");
        map.put("key3", "value3");
        // 1. 遍历所有键值对
        System.out.println("=== 遍历方式 ===");
        // 方式1:使用entrySet
        for (Map.Entry<String, String> entry : map.entrySet()) {
            System.out.println(entry.getKey() + " -> " + entry.getValue());
        }
        // 方式2:使用forEach(Java 8+)
        map.forEach((key, value) -> {
            System.out.println(key + " -> " + value);
        });
        // 2. 获取所有key
        Set<String> keys = map.keySet();
        System.out.println("所有key:" + keys);
        // 3. 检查是否包含
        System.out.println("是否包含key1:" + map.containsKey("key1"));
        System.out.println("是否包含value1:" + map.containsValue("value1"));
        // 4. 计算操作(Java 8+)
        String key = "key1";
        // 如果key存在则处理,不存在则添加
        map.compute(key, (k, v) -> v == null ? "default" : v + "_processed");
        // 如果key不存在,添加默认值
        map.computeIfAbsent("key4", k -> "default_value");
        // 如果key存在,对值进行处理
        map.computeIfPresent("key2", (k, v) -> v + "_updated");
        System.out.println("计算操作后:" + map);
        // 5. 合并操作
        Map<String, Integer> map1 = new HashMap<>();
        map1.put("a", 1);
        map1.put("b", 2);
        Map<String, Integer> map2 = new HashMap<>();
        map2.put("b", 3);
        map2.put("c", 4);
        // 合并map2到map1,重复的key用新值
        map1.putAll(map2);
        System.out.println("合并后:" + map1);
        // 合并并处理重复值
        Map<String, Integer> map3 = new HashMap<>();
        map3.put("x", 10);
        map3.put("y", 20);
        Map<String, Integer> map4 = new HashMap<>();
        map4.put("y", 30);
        map4.put("z", 40);
        map4.forEach((k, v) -> {
            map3.merge(k, v, Integer::sum); // 重复的key值相加
        });
        System.out.println("合并并求和后:" + map3);
    }
}

实战案例:学生成绩管理系统

import java.util.*;
public class StudentScoreManager {
    private Map<String, Map<String, Integer>> studentScores = new HashMap<>();
    // 添加学生成绩
    public void addScore(String studentName, String subject, int score) {
        studentScores.computeIfAbsent(studentName, k -> new HashMap<>())
                     .put(subject, score);
        System.out.println("添加成功:" + studentName + "的" + subject + "成绩为" + score);
    }
    // 查询学生成绩
    public Map<String, Integer> getStudentScores(String studentName) {
        return studentScores.getOrDefault(studentName, Collections.emptyMap());
    }
    // 查询某科最高分
    public void getSubjectHighScore(String subject) {
        int maxScore = Integer.MIN_VALUE;
        String bestStudent = "";
        for (Map.Entry<String, Map<String, Integer>> entry : studentScores.entrySet()) {
            Integer score = entry.getValue().get(subject);
            if (score != null && score > maxScore) {
                maxScore = score;
                bestStudent = entry.getKey();
            }
        }
        if (maxScore != Integer.MIN_VALUE) {
            System.out.println(subject + "最高分:" + maxScore + ",由" + bestStudent + "获得");
        } else {
            System.out.println("暂无" + subject + "成绩");
        }
    }
    // 计算平均分
    public void printAverageScore() {
        studentScores.forEach((name, scores) -> {
            if (!scores.isEmpty()) {
                double avg = scores.values().stream()
                                  .mapToInt(Integer::intValue)
                                  .average()
                                  .orElse(0.0);
                System.out.println(name + "平均分:" + String.format("%.2f", avg));
            }
        });
    }
    public static void main(String[] args) {
        StudentScoreManager manager = new StudentScoreManager();
        // 添加数据
        manager.addScore("张三", "数学", 95);
        manager.addScore("张三", "语文", 88);
        manager.addScore("李四", "数学", 92);
        manager.addScore("李四", "语文", 90);
        manager.addScore("王五", "数学", 85);
        // 查询数据
        System.out.println("\n张三的成绩:" + manager.getStudentScores("张三"));
        System.out.println("\n各科最高分:");
        manager.getSubjectHighScore("数学");
        manager.getSubjectHighScore("语文");
        System.out.println("\n平均分:");
        manager.printAverageScore();
    }
}

存储(put)

Java HashMap案例如何存取值

  • 正常存储:map.put(key, value)
  • 条件存储:map.putIfAbsent(key, value)
  • key已存在会覆盖旧值

获取(get)

  • 正常获取:map.get(key),不存在返回null
  • 安全获取:map.getOrDefault(key, defaultValue)
  • 检查存在:map.containsKey(key)

修改(update)

  • 直接赋值:map.put(key, newValue)
  • 存在时修改:map.replace(key, newValue)
  • 条件修改:map.replace(key, oldValue, newValue)

删除(delete)

  • 直接删除:map.remove(key)
  • 条件删除:map.remove(key, value)
  • 清空:map.clear()

抱歉,评论功能暂时关闭!