java 如何将字符串附加到 HashMap 元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5420393/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 11:02:12  来源:igfitidea点击:

How to append a string to a HashMap element?

javahashmap

提问by aneuryzm

I have a hashmap in java and I need to append a string to one specific key. Is this code correct ? Or it is not a good practice to invoke .get method to retrieve the original content ?

我在 java 中有一个哈希图,我需要将一个字符串附加到一个特定的键上。这段代码正确吗?或者调用 .get 方法来检索原始内容不是一个好习惯?

myMap.put("key", myMap.get("key") + "new content") ;

thanks

谢谢

回答by Jon Skeet

If you mean you want to replace the current value with a new value, that's absolutely fine.

如果您的意思是想用新值替换当前值,那绝对没问题。

Just be aware that if the key doesn't exist, you'll end up with "nullnew content" as the new value, which may not be what you wanted. You maywant to do:

请注意,如果键不存在,您最终将使用“nullnew content”作为新值,这可能不是您想要的。你可能想做:

String existing = myMap.get("key");
String extraContent = "new content";
myMap.put("key", existing == null ? extraContent : existing + extraContent);

回答by aioobe

I have a hashmap in java and I need to append a string to one specific key.

我在 java 中有一个哈希图,我需要将一个字符串附加到一个特定的键上。

You will need to remove the mapping, and add a new mapping with the updated key. This can be done in one line as follows.

您将需要删除映射,并使用更新的密钥添加新映射。这可以在一行中完成,如下所示。

myMap.put(keyToUpdate + toAppend, myMap.remove(keyToUpdate));

The Map.removemethod removes a mapping, and returns the previously mapped value

Map.remove方法移除一个映射,并返回之前映射的值

回答by Peter Lawrey

If you do this often you may wish to use StringBuilder.

如果您经常这样做,您可能希望使用 StringBuilder。

Map<String, StringBuilder> map = new LinkedHashMap<String, StringBuilder>();

StringBuilder sb = map.get(key);
if (sb == null)
   map.put(key, new StringBuilder(toAppend));
else
   sb.append(toAppend);