How to append a string to a HashMap element?
Solution 1
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);
Solution 2
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
Solution 3
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);
aneuryzm
Updated on June 23, 2022Comments
-
aneuryzm about 2 years
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 ?
myMap.put("key", myMap.get("key") + "new content") ;
thanks
-
aioobe over 13 years"I need to append a string to one specific key." Your solution appends to a value in the map.
-
Jon Skeet over 13 years@aioobe: I interpreted that as "I need to append a string to the value associated with one specific key". Maybe the OP will clarify...