掌握JDK1.8版本中为HashMap添加的骚操作

getOrDefault

方法

default V getOrDefault(Object key, V defaultValue)

含义

根据Key获取Value,如果获取不到,则返回指定的defaultValue

示例

正常我们要先使用containsKey方法判断Key是否存在,如果存在才可根据Key获取Value,再返回。

java 复制代码
public static void main(String[] args) {
    Map<String, String> map = new HashMap<>();
    map.put("name", "lisi");

    String value = "zhangsan";
    if (map.containsKey("name")) {
        value = map.get("name");
    }

    System.out.println(value);
}

使用getOrDefault方法,一步到位。

java 复制代码
public static void main(String[] args) {
    Map<String, String> map = new HashMap<>();
    String value = map.getOrDefault("name", "zhangsan");
    System.out.println(value);
}

统计每个字符出现的次数,使用getOrDefault非常方便。

java 复制代码
public static void main(String[] args) {
    List<String> chars = Arrays.asList("a", "b", "a", "c", "a", "d", "a", "e");
    Map<String, Integer> map = new HashMap<>();
    for (String str : chars) {
        map.put(str, map.getOrDefault(str, 0) + 1);
    }
    System.out.println(map);
}

computeIfAbsent

方法

default V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction)

含义

根据Key查找,如果Key存在,则什么也不做,如果Key不存在,则将Value添加进去。

示例

以下返回的是{hobby=[dance, sing, draw]},也就是说在使用computeIfAbsent时,如果Key已经存在则不会操作对应的Value

java 复制代码
public static void main(String[] args) {
    Map<String, List<String>> map = new HashMap<>();
    List<String> hobbyValues = map.computeIfAbsent("hobby", v -> Lists.newArrayList("dance", "sing", "draw"));
    System.out.println(hobbyValues);
    map.computeIfAbsent("hobby", v -> Lists.newArrayList("basketball"));
    System.out.println(map);
}

输出

java 复制代码
[dance, sing, draw]
{hobby=[dance, sing, draw]}

computeIfPresent

方法

default V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction)

含义

computeIfPresentcomputeIfAbsent刚好相反,computeIfPresent是如果Key存在就用新Value替换老Value,如果不存在则什么也不做,而computeIfAbsent是如果Key存在就什么也不做,如果Key不存在,则使用新Value

示例

java 复制代码
public static void main(String[] args) {
    Map<String, List<String>> map = new HashMap<>();
    // 因为key不存在,所以什么也不做
    List<String> hobbyValue = map.computeIfPresent("hobby", (k, v) -> Lists.newArrayList("basketball"));
    System.out.println(hobbyValue);
    System.out.println(map);
    System.out.println();
    
    // 因为key不存在,所以将value添加到map中
    List<String> hobbyValues = map.computeIfAbsent("hobby", v -> Lists.newArrayList("dance", "sing", "draw"));
    System.out.println(hobbyValues);
    System.out.println(map);
    System.out.println();
    
    // 因为key存在,所以用新value替换老value
    hobbyValue = map.computeIfPresent("hobby", (k, v) -> Lists.newArrayList("basketball"));
    System.out.println(hobbyValue);
    System.out.println(map);
}

输出

java 复制代码
null
{}

[dance, sing, draw]
{hobby=[dance, sing, draw]}

[basketball]
{hobby=[basketball]}

compute

方法

default V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction)

含义

不考虑Key存不存在,直接替换为新Value

示例

java 复制代码
public static void main(String[] args) {
    Map<String, List<String>> map = new HashMap<>();

    List<String> hobbyValue = map.compute("hobby", (k, v) -> Lists.newArrayList("basketball"));
    System.out.println(hobbyValue);
    System.out.println(map);
    System.out.println();

}

输出

java 复制代码
[basketball]
{hobby=[basketball]}

replace

方法

default V replace(K key, V value)

boolean replace(K key, V oldValue, V newValue)

含义

replace方法,实现的功能和computeIfPresent类似,只不过computeIfPresent入参是BiFunction函数接口,更灵活一些,而replace入参则是具体的Value类型。

示例

存在hobby就替换,否则什么也不做。

java 复制代码
map.replace("hobby", new ArrayList<>());
java 复制代码
public static void main(String[] args) {
    Map<String, String> map = new HashMap<>();
    map.put("name", "zhangsan");
    map.replace("name", "zhangsan", "lisi");
    System.out.println(map);
}

replaceAll

方法

default void replaceAll(BiFunction<? super K, ? super V, ? extends V> function)

含义

该方法可以一次性替换所有Value,这通常用于需要对Value进行统一处理时。

示例

java 复制代码
public static void main(String[] args) {
    Map<String, List<String>> map = new HashMap<>();
    map.put("hobby_1", Lists.newArrayList("dance", "sing", "draw"));
    map.put("hobby_2", Lists.newArrayList("swim", "football", "basketball"));
    System.out.println(map);
    map.replaceAll((k, v) -> v.stream().sorted().collect(Collectors.toList()));
    System.out.println(map);
}

输出

java 复制代码
排序前:{hobby_2=[swim, football, basketball], hobby_1=[dance, sing, draw]}
排序后:{hobby_2=[basketball, football, swim], hobby_1=[dance, draw, sing]}

putIfAbsent

方法

default V putIfAbsent(K key, V value)

含义

putIfAbsent方法,实现功能又和computeIfAbsent类似,区别同样是computeIfAbsent入参是函数接口。 如果Key存在,则什么也不做,返回Key对应的Value,如果Key不存在,则将Value添加进去,并返回null

示例

java 复制代码
public static void main(String[] args) {
    Map<String, List<String>> map = new HashMap<>();
    map.put("hobby_1", Lists.newArrayList("dance", "sing", "draw"));
    List<String> hobby_1 = map.putIfAbsent("hobby_1", Lists.newArrayList("swim", "football", "basketball"));
    System.out.println(hobby_1);
    List<String> hobby_2 = map.putIfAbsent("hobby_2", Lists.newArrayList("swim", "football", "basketball"));
    System.out.println(hobby_2);
    System.out.println(map);
}

输出

java 复制代码
[dance, sing, draw]
null
{hobby_2=[swim, football, basketball], hobby_1=[dance, sing, draw]}

merge

方法

default V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction)

含义

merge方法可以在原Value的基础上继续操作。

示例

java 复制代码
public static void main(String[] args) {
    Map<String, List<String>> map = new HashMap<>();
    map.put("hobby_1", Lists.newArrayList("dance", "sing", "draw"));
    map.merge("hobby_1", Lists.newArrayList("swim", "football", "basketball", "dance"), MapUtils::apply);
    System.out.println(map);
}
private static List<String> apply(List<String> oldValue, List<String> newValue) {
    oldValue.addAll(newValue);
    return oldValue.stream().distinct().collect(Collectors.toList());
}

输出

java 复制代码
{hobby_1=[dance, sing, draw, swim, football, basketball]}

forEach

方法

default void forEach(BiConsumer<? super K, ? super V> action)

含义

forEach方法提供了便捷的遍历mapKeyValue的方式。

示例

java 复制代码
public static void main(String[] args) {
    Map<String, List<String>> map = new HashMap<>();
    map.put("hobby_1", Lists.newArrayList("dance", "sing", "draw"));
    map.put("hobby_2", Lists.newArrayList("swim", "football", "basketball"));
    map.put("hobby_3", Lists.newArrayList("run"));
    map.forEach((k, v) -> System.out.println(k + ": " + v.size()));
}

输出

java 复制代码
hobby_2: 3
hobby_1: 3
hobby_3: 1
相关推荐
曼巴UE510 分钟前
UE5 C++ JSON 最简单,麻烦的方式,直接读存(一)
java·服务器·前端
QMY52052033 分钟前
什么是爬虫?
java·eclipse
bbq粉刷匠33 分钟前
力扣--两数之和(Java)
java·leetcode
IT_陈寒34 分钟前
React 19新特性实战:5个提升开发效率的技巧与避坑指南
前端·人工智能·后端
mzlogin35 分钟前
解决访问 https 网站时,后端重定向或获取 URL 变成 http 的问题
java·后端·nginx
江湖独行侠39 分钟前
认知神经科学解释生活中的现象——白月光、朱砂痣
java·服务器·生活·情绪
paopao_wu40 分钟前
DeepSeek-OCR实战(06):SpringBoot应用接入
java·spring boot·ai·ocr·deepseek
せいしゅん青春之我1 小时前
【JavaEE初阶】IP协议-IP地址不够用了咋办?
java·服务器·网络·网络协议·tcp/ip·java-ee
醇氧1 小时前
MAC 安装openJDK8
java·开发语言
海阔天空在前走1 小时前
JAVA中六种策略模式的实现
java·开发语言·策略模式