computeIfAbsent 是 Map 接口里的一个方法,它的作用是在给定的键不存在于 Map 中时,计算一个值并将其关联到该键;若键已经存在,就直接返回与之关联的值。
1.统计单词出现次数
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;否则,将其出现次数加 1wordCount.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.分组对象
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.缓存数据
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 方法从数据源获取数据,并将其存储到缓存中;如果存在,直接从缓存中获取数据。