Java HashMap computeIfPresent()方法

java.util.HashMap.computeIfPresent() 如果指定键的值存在且非空,则用于给定键及其当前映射值的情况下计算新映射。

1 语法

public Object computeIfPresent(Object key,BiFunction remappingFunction)

2 参数

key:与值关联的键。

remappingFunction:对值进行运算的函数。

3 返回值

此方法返回与指定键关联的新的重新映射的值;如果映射返回null,则返回null。

4 示例 

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * java.util.HashMap.computeIfPresent()方法的例子
 */
import java.util.*;

public class Demo {
    public static void main(String args[]) {

        // Create a HashMap and add some values
        HashMap<String, Integer> wordCount = new HashMap<>();
        wordCount.put("Yiidian", 1);
        wordCount.put("for", 2);
        wordCount.put("Java", 3);

        // print HashMap details
        System.out.println("Hashmap before operation :\n "
                + wordCount);

        // provide new value for keys which is present
        // using computeIfPresent method
        wordCount.computeIfPresent("Yiidian",
                (key, val) -> val + 100);

        // print new mapping
        System.out.println("HashMap after operation :\n " + wordCount);
    }
}

输出结果为:

Hashmap before operation :
 {Java=3, Yiidian=1, for=2}
HashMap after operation :
 {Java=3, Yiidian=101, for=2}

热门文章

优秀文章