Java Hashtable computeIfPresent()方法
java.util.Hashtable.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.Hashtable.computeIfPresent()方法的例子
*/
import java.util.*;
public class Demo {
public static void main(String args[]) {
// Create a Hashtable and add some values
Hashtable<String, Integer> wordCount = new Hashtable<>();
wordCount.put("Yiidian", 1);
wordCount.put("for", 2);
wordCount.put("Java", 3);
// print Hashtable details
System.out.println("Hashtable 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("Hashtable after operation :\n " + wordCount);
}
}
输出结果为:
Hashtable before operation :
{Java=3, for=2, Yiidian=1}
Hashtable after operation :
{Java=3, for=2, Yiidian=101}
热门文章
优秀文章