computeIfAbsent使用示例

computeIfAbsent 是 Map 接口里的一个方法,它的作用是在给定的键不存在于 Map 中时,计算一个值并将其关联到该键;若键已经存在,就直接返回与之关联的值。

1.统计单词出现次数

java 复制代码
import java.util.HashMap;
import java.util.Map;

public class WordCountExample {
    public static void main(String[] args) {
        String[] words = {"apple", "banana", "apple", "cherry", "banana", "apple"};
        Map<String, Integer> wordCount = new HashMap<>();

        for (String word : words) {
            // 如果单词不在 map 中,将其出现次数初始化为 1;否则,将其出现次数加 1
            wordCount.computeIfAbsent(word, k -> 0);
            wordCount.put(word, wordCount.get(word) + 1);
        }

        // 输出每个单词及其出现次数
        for (Map.Entry<String, Integer> entry : wordCount.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
    }
}

遍历单词数组,对于每个单词,使用 computeIfAbsent 方法检查该单词是否已经在 Map 中。如果不在,将其初始出现次数设为 0。

然后通过 put 方法将该单词的出现次数加 1。

最后遍历 Map 并输出每个单词及其出现次数。

2.分组对象

java 复制代码
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

class Person {
    private String city;
    private String name;

    public Person(String city, String name) {
        this.city = city;
        this.name = name;
    }

    public String getCity() {
        return city;
    }

    public String getName() {
        return name;
    }
}

public class GroupingExample {
    public static void main(String[] args) {
        List<Person> people = new ArrayList<>();
        people.add(new Person("New York", "Alice"));
        people.add(new Person("Los Angeles", "Bob"));
        people.add(new Person("New York", "Charlie"));

        Map<String, List<Person>> peopleByCity = new HashMap<>();

        for (Person person : people) {
            // 如果城市不在 map 中,创建一个新的列表;否则,获取现有的列表
            peopleByCity.computeIfAbsent(person.getCity(), k -> new ArrayList<>()).add(person);
        }

        // 输出每个城市及其对应的人员列表
        for (Map.Entry<String, List<Person>> entry : peopleByCity.entrySet()) {
            System.out.println(entry.getKey() + ":");
            for (Person person : entry.getValue()) {
                System.out.println("  - " + person.getName());
            }
        }
    }
}

使用 computeIfAbsent 方法检查该城市是否已经在 Map 中。如果不在,创建一个新的 ArrayList 用于存储该城市的人员;如果存在,获取现有的列表。然后将该人员添加到对应的列表中。

3.缓存数据

java 复制代码
import java.util.HashMap;
import java.util.Map;

class DataFetcher {
    // 模拟从数据库或其他数据源获取数据
    public String fetchData(String key) {
        System.out.println("Fetching data for key: " + key);
        return "Data for " + key;
    }
}

public class CacheExample {
    public static void main(String[] args) {
        Map<String, String> cache = new HashMap<>();
        DataFetcher fetcher = new DataFetcher();

        String key1 = "key1";
        String key2 = "key2";

        // 第一次获取 key1 的数据,会从数据源获取并缓存
        String data1 = cache.computeIfAbsent(key1, fetcher::fetchData);
        System.out.println("Data for " + key1 + ": " + data1);

        // 再次获取 key1 的数据,会直接从缓存中获取
        String cachedData1 = cache.computeIfAbsent(key1, fetcher::fetchData);
        System.out.println("Cached data for " + key1 + ": " + cachedData1);

        // 获取 key2 的数据,会从数据源获取并缓存
        String data2 = cache.computeIfAbsent(key2, fetcher::fetchData);
        System.out.println("Data for " + key2 + ": " + data2);
    }
}

使用 computeIfAbsent 方法检查该键是否已经在缓存中。如果不在,调用 DataFetcher 的 fetchData 方法从数据源获取数据,并将其存储到缓存中;如果存在,直接从缓存中获取数据。

相关推荐
csbysj202016 小时前
DOM 节点
开发语言
用户849137175471616 小时前
ThreadLocal 源码深度解析:JDK 设计者的“妥协”与“智慧”
java·后端
用户03048059126316 小时前
# 【Maven避坑】源码去哪了?一文看懂 Maven 工程与打包后的目录映射关系
java·后端
小尧嵌入式17 小时前
C++基础语法总结
开发语言·c++·stm32·单片机·嵌入式硬件·算法
@游子17 小时前
Python学习笔记-Day2
开发语言·python
v***553417 小时前
springboot使用logback自定义日志
java·spring boot·logback
qq_3363139317 小时前
java基础-集合进阶
java·开发语言·windows
稚辉君.MCA_P8_Java17 小时前
Gemini永久会员 归并排序(Merge Sort) 基于分治思想(Divide and Conquer)的高效排序算法
java·linux·算法·spring·排序算法
q***188417 小时前
Spring Boot中的404错误:原因、影响及处理策略
java·spring boot·后端
222you17 小时前
MybatisPlus常用注解
java·开发语言·spring