Java HashMap: adding to arraylist

10,260

Solution 1

You have to get the array list out first:

ArrayList<String> list = fileRank.get(word);
list.add(file1);

Of course, it becomes more complicated if you don't know whether there is an entry for that key yet.

ArrayList<String> list = fileRank.get(word);
if (list == null) {
    list = new ArrayList<String>();
    fileRank.put(word, list);
}
list.add(file1);

Solution 2

You ask the map for the value for a certain key, which is an ArrayList, on which you can call add.

String key = "myKey";
fileRank.put( key, new ArrayList<String>() );
//...
fileRank.get( key ).add( "a value");

Solution 3

Get the ArrayList based on the String key, do add() to the ArrayList and then put it back into the HashMap (optional, since the map already holds the reference to it);

fileRank.get(word).add(String)
fileRank.put(work, list);
Share:
10,260
DomX23
Author by

DomX23

Updated on June 07, 2022

Comments

  • DomX23
    DomX23 about 2 years

    I'm using the HashMap class and it looks like this:

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

    I'm wondering how to add a new String into the Arraylist after the initial put.

    fileRank.put(word, file1);
    

    I would like to add file2 after file1 to the key: word from above.

  • Bhesh Gurung
    Bhesh Gurung over 12 years
    Why put it back again? Is it necessary?
  • Mechkov
    Mechkov over 12 years
    You dont have to. Edited my post, thought it is more readable this way.