这是在 Java 8 和 9 中连接映射中的字符串值的最便捷方法。我目前在项目中拥有以下代码:
private static void addToMap2(Map<String, ? super CharSequence> invalidMap, String key, String newMessage) {
if (invalidMap.containsKey(key)) {
invalidMap.put(key, invalidMap.get(key) + " and " + newMessage);
} else {
invalidMap.put(key, newMessage);
}
}
这段代码真的相当于:
private static void addToMap3(Map<String, ? super CharSequence> invalidMap, String key, String value) {
invalidMap.merge(key, value, (s, s2) -> s + " and " + s2);
}
?
还有其他更好的选择吗?
最佳答案
是的,这两种方法应该(大致)等效,如 JavaDoc 中所述(由我强调):
If the specified key is not already associated with a value or is associated with null, associates it with the given non-null value. Otherwise, replaces the associated value with the results of the given remapping function, or removes if the result is null.
事实上,有一个细微的差别:如果 map 已包含指定键的 null
,您将不会获得值 "null and xxx"
,其中 xxx
可以是 null
或任何其他字符串。相反,如果 value
为 null
,您会得到 NullPointerException,或者只是添加 value
。
如果您查看 Map.merge(...)
的源代码,您会看到以下内容:
V oldValue = get(key);
V newValue = (oldValue == null) ? value :
remappingFunction.apply(oldValue, value);
if(newValue == null) {
remove(key);
} else {
put(key, newValue);
}
为了更类似于您的第一个方法,可以将其写为:
V oldValue = containsKey(key) ? get(key) : null;
V newValue = (oldValue == null) ? value :
remappingFunction.apply(oldValue, value);
if(newValue == null) {
remove(key);
} else {
put(key, newValue);
}
请注意,`` 将是您传递的 lambda,相当于 invalidMap.get(key) + "and "+ newMessage
(s + "and"+ s2
)。因此,如果您用 lambda 替换该函数,您将得到如下所示的结果:
V oldValue = containsKey(key) ? get(key) : null;
V newValue = (oldValue == null) ? value :
oldValue + " and " + value; //oldValue would be s and value would be s2
if(newValue == null) {
remove(key);
} else {
put(key, newValue);
}
话虽这么说,您需要确保 map 不包含值为 null
的键,或者根据您的需要进行处理。
关于java - Java 中通过键连接字符串值的最方便的习惯用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46648456/