Java computeIfAbsent 使用例子
Java 8 中的 computeIfAbsent() 方法可以用于在 Map 中设置默认值,如果键不存在。
以下是一个示例,演示如何使用 computeIfAbsent() 方法:
import java.util.HashMap;
import java.util.Map;
public class ComputeIfAbsentExample {
public static void main(String[] args) {
Map<String, Integer> wordCount = new HashMap<>();
// 使用 computeIfAbsent() 方法将默认值设置为 0
wordCount.computeIfAbsent("apple", k -> 0);
wordCount.computeIfAbsent("banana", k -> 0);
wordCount.computeIfAbsent("orange", k -> 0);
// 增加计数器
wordCount.computeIfPresent("apple", (k, v) -> v + 1);
wordCount.computeIfPresent("banana", (k, v) -> v + 1);
wordCount.computeIfPresent("orange", (k, v) -> v + 1);
wordCount.computeIfPresent("mango", (k, v) -> v + 1);
// 打印结果
wordCount.forEach((k, v) -> System.out.println(k + " : " + v));
}
}
输出结果:
orange : 1
banana : 1
apple : 1
在上面的示例中,我们首先创建了一个空的 HashMap 对象 wordCount,然后使用 computeIfAbsent() 方法将默认值设置为 0,这意味着如果一个键不存在,它的值将被设置为 0。
然后,我们使用 computeIfPresent() 方法增加计数器,并在最后打印结果。
原文地址: https://www.cveoy.top/t/topic/bsQR 著作权归作者所有。请勿转载和采集!