[Java Usage] Use of computeIfAbsent()

1. Background description

This kind of data structure is often encountered in programming. It is judged whether the key exists in a map. If it exists, the value data is processed. If it does not exist, a data structure that meets the value requirements is created and placed in the value. Before JDK1.7, this was often done. The function was achievable, but the code was not elegant enough.

2. Function discovery

So, after the test of time, it finally came out after repeated calls, and was added inJava8 version a> A new method is added to the Map interface, which is used to obtain the corresponding value in the Map according to the specified key. If the key does not exist, use the specified function to calculate a Default value and store it in Map, finally return the default value. Java8 iscomputeIfAbsent() This API, computeIfAbsent()

The syntax is as follows:

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

Among them, key represents the key to obtain the value, mappingFunction Represents a function that calculates the default value. Specifically, if the specified key already exists in Map, the value corresponding to the key will be returned directly; otherwise, use mappingFunction calculates a default value, stores the key and default value into Map, and finally returns the default value.

3. Sample code

The sample code is as follows:

import java.util.HashMap;
import java.util.Map;

public class TestComputeIfAbsent {
    
    

    public static void main(String[] args) {
    
    
        Map<String, Integer> map = new HashMap<>();
        map.put("apple", 1);
        map.put("banana", 2);

        int orangeCount = map.computeIfAbsent("orange", k -> 0);
        System.out.println(orangeCount); // 输出 0

        int appleCount = map.computeIfAbsent("apple", k -> 0);
        System.out.println(appleCount); // 输出 1
    }

}

In the above example, a Map object is first created and two key-value pairs are added to it. Then, use the computeIfAbsent() method to obtain the value corresponding to a non-existent key "orange". Since the key does not exist, the specified function is used k -> 0 calculates a default value of 0, stores the key and default value in the Map, and finally returns the default value. Next, use the computeIfAbsent() method to obtain the value corresponding to an existing key "apple". Since the key already exists, the value is returned directly. The value corresponding to the key is 1.

The end of this article!

Supongo que te gusta

Origin blog.csdn.net/weixin_44299027/article/details/133995734
Recomendado
Clasificación