wood burning stoves 2.0
The moose likes Beginning Java and the fly likes Adding values to a list already against already existing key in HashMap Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Adding values to a list already against already existing key in HashMap" Watch "Adding values to a list already against already existing key in HashMap" New topic
Author

Adding values to a list already against already existing key in HashMap

Aditya Sirohi
Ranch Hand

Joined: Jan 05, 2010
Posts: 93

Hello Folks,

I have a question. I declared a HashMap like:-

HashMap<String, ArrayList> map = new HashMap<String, ArrayList>();

ArrayList test = new ArrayList();
test.add("hardwork");
test.add("dedication");
map.put("sucess", test );

Now the data is like this in the Map
Key Value
sucess [harwork, dedication]

If i want to add values X and Y to the key "sucess", so that the value is like [harwork, dedication, X, Y]. How do i do it?

-Aditya
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4541
    
    8

get(key) is the way to extract a single value from a Map, which in this case will return an ArrayList. So you can do this:
Aditya Sirohi
Ranch Hand

Joined: Jan 05, 2010
Posts: 93

success

Thanks
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 20080
    
  30

If you're not sure if the key is already present you can use the following technique:


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6 - OCEJPAD 6
How To Ask Questions How To Answer Questions
 
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com
 
subject: Adding values to a list already against already existing key in HashMap
 
It's not a secret anymore!