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 方法从数据源获取数据,并将其存储到缓存中;如果存在,直接从缓存中获取数据。

相关推荐
Season4501 小时前
C++11并发支持库(condition_variable | future全家桶)
java·jvm·c++
阿Y加油吧2 小时前
二刷 LeetCode:爬楼梯与杨辉三角,Java 实现复盘
java·算法·leetcode
落羽的落羽2 小时前
【项目】C++从零实现JsonRpc框架——项目引入
linux·服务器·开发语言·c++·人工智能·算法·机器学习
墨月白2 小时前
【Python】程序设计基本方法
开发语言·python
不知名的忻2 小时前
堆排序(Java)
java·数据结构·算法·排序算法
TAN-90°-2 小时前
Java 5——final 抽象 接口
java·开发语言
Andy2 小时前
C++ 容器适配器_栈_队列_双端队列
开发语言·网络·c++
吴声子夜歌2 小时前
Java——显示锁
java·开发语言
思麟呀2 小时前
在C++基础上理解Csharp-2
开发语言·jvm·c++·c#
桀人2 小时前
类和对象——上篇
开发语言·c++