Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append a string to a HashMap element?

Tags:

java

hashmap

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

like image 901
aneuryzm Avatar asked Mar 24 '11 14:03

aneuryzm


1 Answers

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);
like image 141
Jon Skeet Avatar answered Sep 21 '22 13:09

Jon Skeet