Java案例如何使用HashMap?

wen java案例 11

本文目录导读:

Java案例如何使用HashMap?

  1. Java HashMap 使用案例
  2. 基础使用案例
  3. 遍历HashMap的多种方式
  4. 学生成绩管理系统案例
  5. 单词计数器案例
  6. 缓存实现案例
  7. HashMap 常用方法和注意事项

Java HashMap 使用案例

HashMap 是 Java 中最常用的集合类之一,下面通过几个实际案例来演示如何使用。

基础使用案例

import java.util.HashMap;
import java.util.Map;
public class BasicHashMapExample {
    public static void main(String[] args) {
        // 1. 创建HashMap
        HashMap<String, Integer> scores = new HashMap<>();
        // 2. 添加元素
        scores.put("张三", 95);
        scores.put("李四", 88);
        scores.put("王五", 92);
        scores.put("赵六", 78);
        // 3. 获取元素
        System.out.println("张三的成绩: " + scores.get("张三"));
        // 4. 判断是否包含key
        boolean hasLiSi = scores.containsKey("李四");
        System.out.println("是否包含李四: " + hasLiSi);
        // 5. 判断是否包含value
        boolean hasScore95 = scores.containsValue(95);
        System.out.println("是否有95分: " + hasScore95);
        // 6. 获取大小
        System.out.println("学生人数: " + scores.size());
        // 7. 删除元素
        scores.remove("赵六");
        System.out.println("删除赵六后人数: " + scores.size());
        // 8. 清空HashMap
        // scores.clear();
    }
}

遍历HashMap的多种方式

import java.util.HashMap;
import java.util.Map;
public class HashMapIterationExample {
    public static void main(String[] args) {
        HashMap<String, String> cities = new HashMap<>();
        cities.put("北京", "首都");
        cities.put("上海", "魔都");
        cities.put("广州", "羊城");
        cities.put("深圳", "鹏城");
        // 方式1: 使用 entrySet 遍历
        System.out.println("=== 方式1: entrySet ===");
        for (Map.Entry<String, String> entry : cities.entrySet()) {
            System.out.println(entry.getKey() + " -> " + entry.getValue());
        }
        // 方式2: 使用 keySet 遍历
        System.out.println("\n=== 方式2: keySet ===");
        for (String key : cities.keySet()) {
            System.out.println(key + " -> " + cities.get(key));
        }
        // 方式3: 使用 values 遍历
        System.out.println("\n=== 方式3: values ===");
        for (String value : cities.values()) {
            System.out.println("城市别称: " + value);
        }
        // 方式4: 使用 Lambda 表达式 (Java 8+)
        System.out.println("\n=== 方式4: Lambda ===");
        cities.forEach((key, value) -> {
            System.out.println(key + " -> " + value);
        });
        // 方式5: 使用 Stream API (Java 8+)
        System.out.println("\n=== 方式5: Stream API ===");
        cities.entrySet().stream()
              .filter(entry -> entry.getKey().startsWith("北"))
              .forEach(System.out::println);
    }
}

学生成绩管理系统案例

import java.util.HashMap;
import java.util.Map;
import java.util.ArrayList;
import java.util.List;
public class StudentGradeSystem {
    private HashMap<String, ArrayList<Integer>> studentGrades;
    public StudentGradeSystem() {
        studentGrades = new HashMap<>();
    }
    // 添加学生成绩
    public void addGrade(String name, int grade) {
        studentGrades.computeIfAbsent(name, k -> new ArrayList<>()).add(grade);
    }
    // 获取学生平均分
    public double getAverage(String name) {
        ArrayList<Integer> grades = studentGrades.get(name);
        if (grades == null || grades.isEmpty()) {
            return 0.0;
        }
        return grades.stream().mapToInt(Integer::intValue).average().orElse(0.0);
    }
    // 获取所有学生的平均分
    public Map<String, Double> getAllAverages() {
        Map<String, Double> averages = new HashMap<>();
        for (Map.Entry<String, ArrayList<Integer>> entry : studentGrades.entrySet()) {
            averages.put(entry.getKey(), getAverage(entry.getKey()));
        }
        return averages;
    }
    // 打印所有成绩
    public void printAllGrades() {
        studentGrades.forEach((name, grades) -> {
            System.out.println(name + ": " + grades + " (平均分: " + getAverage(name) + ")");
        });
    }
    public static void main(String[] args) {
        StudentGradeSystem system = new StudentGradeSystem();
        // 添加学生成绩
        system.addGrade("张三", 85);
        system.addGrade("张三", 90);
        system.addGrade("张三", 88);
        system.addGrade("李四", 75);
        system.addGrade("李四", 82);
        system.addGrade("王五", 95);
        // 打印所有成绩
        system.printAllGrades();
        // 获取特定学生平均分
        System.out.println("\n张三平均分: " + system.getAverage("张三"));
        // 获取所有学生平均分
        System.out.println("\n所有学生平均分: " + system.getAllAverages());
    }
}

单词计数器案例

import java.util.HashMap;
import java.util.Map;
public class WordCounter {
    public static Map<String, Integer> countWords(String text) {
        Map<String, Integer> wordCount = new HashMap<>();
        // 清理文本并分割单词
        String[] words = text.toLowerCase()
                           .replaceAll("[^a-zA-Z\\s]", "")
                           .split("\\s+");
        for (String word : words) {
            if (!word.isEmpty()) {
                // 方法1: 传统方式
                // if (wordCount.containsKey(word)) {
                //     wordCount.put(word, wordCount.get(word) + 1);
                // } else {
                //     wordCount.put(word, 1);
                // }
                // 方法2: 使用 getOrDefault
                // wordCount.put(word, wordCount.getOrDefault(word, 0) + 1);
                // 方法3: 使用 merge (Java 8+)
                wordCount.merge(word, 1, Integer::sum);
            }
        }
        return wordCount;
    }
    public static void main(String[] args) {
        String text = "Hello World Hello Java Hello World Java Programming";
        Map<String, Integer> wordCount = countWords(text);
        System.out.println("单词统计结果:");
        wordCount.forEach((word, count) -> {
            System.out.println(word + ": " + count + "次");
        });
        // 找出出现次数最多的单词
        String mostFrequent = wordCount.entrySet()
                .stream()
                .max(Map.Entry.comparingByValue())
                .map(Map.Entry::getKey)
                .orElse("无");
        System.out.println("\n出现最多的单词: " + mostFrequent + 
                          " (" + wordCount.get(mostFrequent) + "次)");
    }
}

缓存实现案例

import java.util.HashMap;
import java.util.Map;
public class SimpleCache<K, V> {
    private final Map<K, V> cache = new HashMap<>();
    private final long ttl; // 过期时间(毫秒)
    private final Map<K, Long> timestamps = new HashMap<>();
    public SimpleCache(long ttl) {
        this.ttl = ttl;
    }
    // 添加缓存
    public void put(K key, V value) {
        cache.put(key, value);
        timestamps.put(key, System.currentTimeMillis());
        System.out.println("缓存添加: " + key + " -> " + value);
    }
    // 获取缓存
    public V get(K key) {
        Long timestamp = timestamps.get(key);
        if (timestamp == null) {
            return null;
        }
        // 检查是否过期
        if (System.currentTimeMillis() - timestamp > ttl) {
            cache.remove(key);
            timestamps.remove(key);
            System.out.println("缓存已过期: " + key);
            return null;
        }
        return cache.get(key);
    }
    // 清除过期缓存
    public void clearExpired() {
        long now = System.currentTimeMillis();
        timestamps.entrySet().removeIf(entry -> {
            if (now - entry.getValue() > ttl) {
                cache.remove(entry.getKey());
                return true;
            }
            return false;
        });
    }
    // 获取缓存大小
    public int size() {
        return cache.size();
    }
    public static void main(String[] args) throws InterruptedException {
        // 创建5秒过期时间的缓存
        SimpleCache<String, String> cache = new SimpleCache<>(5000);
        // 添加缓存
        cache.put("user1", "张三");
        cache.put("user2", "李四");
        // 立即获取
        System.out.println("立即获取: " + cache.get("user1"));
        // 等待3秒
        Thread.sleep(3000);
        System.out.println("3秒后获取: " + cache.get("user1"));
        // 等待3秒(总共6秒,超过5秒)
        Thread.sleep(3000);
        System.out.println("6秒后获取: " + cache.get("user1"));
        System.out.println("当前缓存大小: " + cache.size());
        // 清除过期缓存
        cache.clearExpired();
        System.out.println("清除后缓存大小: " + cache.size());
    }
}

HashMap 常用方法和注意事项

import java.util.HashMap;
import java.util.Map;
public class HashMapTipsExample {
    public static void main(String[] args) {
        // 1. 初始化容量和负载因子
        HashMap<String, Integer> map1 = new HashMap<>(16, 0.75f);
        // 2. 使用 putIfAbsent 避免覆盖
        Map<String, String> config = new HashMap<>();
        config.put("timeout", "5000");
        config.putIfAbsent("timeout", "10000"); // 不会覆盖
        System.out.println("timeout: " + config.get("timeout")); // 输出: 5000
        // 3. 使用 computeIfAbsent 懒加载
        Map<String, List<String>> groups = new HashMap<>();
        groups.computeIfAbsent("group1", k -> new ArrayList<>()).add("member1");
        System.out.println("group1: " + groups.get("group1"));
        // 4. 使用 getOrDefault 避免空指针
        Map<String, Integer> scores = new HashMap<>();
        scores.put("张三", 95);
        System.out.println("李四成绩: " + scores.getOrDefault("李四", 0));
        // 5. 使用 replace 方法
        scores.replace("张三", 95, 100); // 只有当值为95时才替换为100
        System.out.println("张三新成绩: " + scores.get("张三"));
        // 6. 合并操作
        scores.merge("张三", 10, Integer::sum); // 如果存在则相加,否则添加
        System.out.println("张三合并后成绩: " + scores.get("张三"));
        // 7. 注意事项:自定义对象作为key时需要重写equals和hashCode
        Map<Person, String> personMap = new HashMap<>();
        personMap.put(new Person("张三", 20), "学生");
        personMap.put(new Person("李四", 25), "老师");
        System.out.println("张三角色: " + personMap.get(new Person("张三", 20)));
    }
    static class Person {
        String name;
        int age;
        Person(String name, int age) {
            this.name = name;
            this.age = age;
        }
        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            Person person = (Person) o;
            return age == person.age && name.equals(person.name);
        }
        @Override
        public int hashCode() {
            return 31 * name.hashCode() + age;
        }
    }
}

HashMap 的主要特点:

  • 基于哈希表实现,查询速度 O(1)
  • 允许 null 键和 null 值
  • 非线程安全
  • 无序(不保证顺序)

使用建议:

  1. 预估容量,避免频繁扩容
  2. 自定义对象作为 key 时重写 equals 和 hashCode
  3. 多线程环境使用 ConcurrentHashMap
  4. 需要有序时使用 LinkedHashMap 或 TreeMap

这些案例涵盖了 HashMap 的常见使用场景,你可以根据实际需求选择合适的实现方式。

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