aspose file tools*
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: 4467
    
    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: 19762
    
  20

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
How To Ask Questions How To Answer Questions
 
 
subject: Adding values to a list already against already existing key in HashMap