Map的compute、computeIfAbsent、computeIfPresent的使用
一、代码例子:
package com.test.collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.function.BiFunction;
import java.util.function.Function;
public class TestMap {
public static void main(String[] args) {
Map<Integer, String> itemMap = new HashMap<>();
itemMap.put(1, "ITEM_WAGNYIYUN");
itemMap.put(2, "QQ_CARD");
itemMap.put(3, "JD_SHOPPING");
System.out.println("=======================compute==========================");
/*
itemMap.compute(1, new BiFunction<Integer, String, String>() {
@Override
public String apply(Integer key, String val) {
return val + key;
}
});*/
itemMap.compute(1, (key, val) -> val + key);
System.out.println(itemMap); //{1=ITEM_WAGNYIYUN1, 2=QQ_CARD, 3=JD_SHOPPING}
//键不存在时插入新条目
itemMap.compute(4, (key, oldVal) -> {
if (oldVal == null) {
return "TM_SHOPPING";
} else {
return oldVal + key;
}
});
System.out.println(itemMap); //{1=ITEM_WAGNYIYUN1, 2=QQ_CARD, 3=JD_SHOPPING, 4=TM_SHOPPING}
//删除条目(当函数返回null时)
itemMap.compute(4, (key, oldVal) -> null);
System.out.println(itemMap); //{1=ITEM_WAGNYIYUN1, 2=QQ_CARD, 3=JD_SHOPPING}
System.out.println("=======================computeIfAbsent==========================");
/**
* computeIfAbsent的使用:
* 仅当键不存在时才计算值
* computeIfAbsent() 只接收键作为参数,而 compute() 接收键和当前值
* computeIfAbsent() 不会删除条目(即使函数返回null)
*/
/*
* 只有当key=1不存在时,才会计算并插入值TM_SHOPPING
itemMap.computeIfAbsent(1, new Function<Integer, String>() {
@Override
public String apply(Integer integer) {
return "TM_SHOPPING";
}
});*/
itemMap.computeIfAbsent(1, integer -> "TM_SHOPPING");
System.out.println(itemMap); //{1=ITEM_WAGNYIYUN1, 2=QQ_CARD, 3=JD_SHOPPING}
String val = itemMap.computeIfAbsent(4, integer -> "TM_SHOPPING");
System.out.println(val); //TM_SHOPPING
System.out.println(itemMap); //{1=ITEM_WAGNYIYUN1, 2=QQ_CARD, 3=JD_SHOPPING, 4=TM_SHOPPING}
Map<String, Set<String>> dictionary = new HashMap<>();
// 添加同义词
dictionary.computeIfAbsent("happy", k -> new HashSet<>()).add("joyful");
dictionary.computeIfAbsent("happy", k -> new HashSet<>()).add("cheerful");
System.out.println(dictionary); //{happy=[cheerful, joyful]}
System.out.println("=======================computeIfAbsent==========================");
/**
* computeIfPresent() - 仅当键存在时才计算值
* 它只在键存在且对应的值不为 null 时,才会计算并更新值。
*
*/
String str = itemMap.computeIfPresent(4, new BiFunction<Integer, String, String>() {
@Override
public String apply(Integer key, String oldVal) {
return oldVal + key;
}
});
System.out.println(str); //TM_SHOPPING4
System.out.println(itemMap); //{1=ITEM_WAGNYIYUN1, 2=QQ_CARD, 3=JD_SHOPPING, 4=TM_SHOPPING4}
String str2 = itemMap.computeIfPresent(5, (k, v) -> v + k);
System.out.println(str2); //null 对不存在的键调用不会有任何效果
System.out.println(itemMap); //{1=ITEM_WAGNYIYUN1, 2=QQ_CARD, 3=JD_SHOPPING, 4=TM_SHOPPING4}
}
}

浙公网安备 33010602011771号