Java中HashMap的一些便捷方法

795 阅读1分钟

业务场景

在使用HashMap的过程中, 我们经常会遇到下面这些业务逻辑:

  1. Map是否为空
  2. 判断key是否存在, 如果存在则获取, 不存在则新增
  3. 判断key是否存在, 如果存在则更新, 不存在则忽略

相信很多小伙伴都经历过, 下面推荐几种笔者认为很优雅的处理方式

解决方案

Map是否为空

public class Test {

    private Map<String, Object> map;

    public void test() {
        map.isEmpty();
    }
}

判断key是否存在, 如果存在则获取, 不存在则新增

这个场景可用于缓存相关, 具体的实现方式有两种, putIfAbsent和computeIfAbsent

putIfAbsent:

public class CacheUtil {

    private Map<String, Student> cache;
    
    private Student getOrCreateByName(String studentName) {
        Student student = Student.builder().name(studentName).build();
        cache.putIfAbsent(studentName, student);
        return student;
    }
    
}

computeIfAbsent:

public class CacheUtil {

    private Map<String, Student> cache;
    
    private Student getOrCreateByName(String studentName) {
        String className = "test-"
        return cache.computeIfAbsent(studentName, key -> className + "student-" + key);
    }
    
}

相信细心的小伙伴已经发现了, computeIfAbsent第二参数实际接收一个function, 并且可以根据外部变量和键值对value进行计算, 所以方法名字是compute嘛

在需要返回本次设置的值时, 使用computeIfAbsent, 在需要返回之前设置的值时, 使用putIfAbsent

判断key是否存在, 如果存在则更新, 不存在则忽略

废话不多说, 直接上代码

public class CacheUtil {

    private Map<String, Student> cache;
    
    private void updateCache(Student student) {
        cache.computeIfPresent(student.getName(), (key, value) -> student);
    }
    
}

注意

上述所有方法都有一定的小坑, 务必注意:

内容putIfAbsentcomputeIfAbsentcomputeIfPresent
方法返回旧值新值新值
key为null生成一个null的key生成一个null的key更新key为null的value
value为null生成一个value为null的key不生成如果旧值为null, 则不变, 如果旧值不为null, 则删除其对应的key