众所周知,Java 8 引入了 Stream API。这是一个非常有用的工具包,但它有一个缺点,它不包含Map。但是,Java 8 向Map接口本身添加了几个有用的方法,以减少“坏”代码的数量。因此,如果您需要对Map中的值执行某些操作,如果它存在于其中,则Java Map 中有一个ComputeIfPresent()方法。如果您需要对不在Map中的值执行某些操作,则可以使用ComputeIfAbsent()方法。我们将在本文中考虑它。
computeIfAbsent() 方法签名
default V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction)
Map (和HashMap)computeIfAbsent ()方法有两个参数。第一个参数是键。第二个参数是mappingFunction。在此方法中,仅当未提供映射时才调用映射函数。
computeIfAbsent() 方法的工作原理
正如我们已经知道的,Map.computeIfAbsent()方法被传递了两个参数,键和用于计算该键的值的函数mappingFunction。这是该方法的逻辑算法:- 该方法首先检查传递的键是否在我们的Map中表示。
- 如果键在Map中表示(并且它不为空),则该方法不执行任何操作。
- 否则,如果键不在Map中表示(或者它为空),则该方法使用键的mappingFunction计算值。
- 如果结果值不为空,则写一个键值对映射。
if (map.get(key) == null)
{
V newValue = mappingFunction.apply(key);
if (newValue != null) map.put(key, newValue);
}
computeIfAbsent() 代码示例
因此,如果该值不在Map中,则该方法将执行更改。让我们看一个简单的例子:
import java.util.HashMap;
import java.util.Map;
//map.computeIfAbsent example
public class ComputeIfAbsentExample {
public static void main(String[] args) {
Map<String, String> myMap = new HashMap<>();
myMap.computeIfAbsent("here is my key", key -> key + ", " + "and this is a new value");
System.out.println(myMap.get("here is my key"));
}
}
输出是:
这是我的钥匙,这是一个新值
现在让我们看看当Map 中有给定值时该方法将做什么。剧透警报:它不会做任何事情。
import java.util.HashMap;
import java.util.Map;
public class ComputeIfAbsentExample2 {
public static void main(String[] args) {
Map<String, String> myMap = new HashMap<>();
myMap.put("here is my key", "and here is my value");
myMap.computeIfAbsent("here is my key", key -> key + ", " + "and this is a new value");
System.out.println(myMap.get("here is my key"));
}
}
这是输出:
这是我的价值
如您所见,该值保持不变。
另一个 ComputeIfAbsent() 示例
如果您熟悉缓存的概念,computeIfAbsent()方法可能会让您想起一些事情。让我们看一个更复杂的解析示例。让我们调用computeIfAbsent()方法两次,以确保在第一种情况下值发生变化,而在第二种情况下则不会。
import java.util.HashMap;
import java.util.Map;
public class ComputeIfAbsentExample {
private static Map<String, Long> numbersMap = new HashMap<>();
public static Long stringToLong(String str) {
return numbersMap.computeIfAbsent(str, key -> {
System.out.println("parsing: " + key);
return Long.parseLong(key);
});
}
public static void main(String[] args) {
// will print:
// > parsing: 10
// > parsing: 25
// > 10+25=35
System.out.println("10+25=" + (stringToLong("10") + stringToLong("25")));
// will print:
// > parsing: 20
// > 10+25=45
// only "20" will be parsed this time, since "25" was already parsed and placed into `numbersMap` map before
System.out.println("20+25=" + (stringToLong("20") + stringToLong("25")));
// will print:
// > 10+20=30
// no parsing will occur, since both "10" and "20" were already parsed and placed into `numbersMap` map before
System.out.println("10+20=" + (stringToLong("10") + stringToLong("20")));
}
}
这是输出:
解析:10 解析:25 10+25=35 解析:20 20+25=45 10+20=30
GO TO FULL VERSION