wood burning stoves*
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


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
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: 4343
    
    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: 19651
    
  18

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
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: Adding values to a list already against already existing key in HashMap
 
Similar Threads
how to store multiple values in one key in hash table
An array name can be changed inside a for statement?
a hashkey for double precision numbers
HashMap
HashMap with Class as value