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
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With