The business scenario

When working with HashMap, we often encounter the following business logic:

  1. Whether Map is empty
  2. Check whether the key exists. If the key exists, obtain it. If the key does not exist, add it
  3. Check whether the key exists. If it does, update it. If it does not, ignore it

I believe that many partners have experienced, the following recommended several I think is very elegant handling

The solution

Whether Map is empty

public class Test {

    private Map<String, Object> map;

    public void test(a) { map.isEmpty(); }}Copy the code

Check whether the key exists. If the key exists, obtain it. If the key does not exist, add it

This scenario can be used for cache correlation, which can be implemented in two ways: putIfAbsent and 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);
        returnstudent; }}Copy the code

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); }}Copy the code

The second parameter computeIfAbsent actually accepts a function and calculates the value based on external variables and key values

ComputeIfAbsent is used when you want to return the value set this time, and putIfAbsent is used when you want to return the value set earlier

Check whether the key exists. If it does, update it. If it does not, ignore it

Without further ado, let’s get right to the code

public class CacheUtil {

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

Pay attention to

All of the above methods have some pitfalls, so be careful:

content putIfAbsent computeIfAbsent computeIfPresent
Method returns The old value The new value The new value
The key is null Generates a null key Generates a null key Update a value whose key is NULL
The value is null Generates a key with value null Does not generate If the old value is null, the value remains unchanged. If the old value is not NULL, the corresponding key is deleted