开发者

How to append a string to a HashMap element?

I have a hashma开发者_如何学编程p 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 ?

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

thanks


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 may want to do:

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


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

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.remove method removes a mapping, and returns the previously mapped value


If you do this often you may wish to use 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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜