Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java HashMap: adding to arraylist

Tags:

java

hashmap

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.

like image 750
DomX23 Avatar asked Dec 28 '22 10:12

DomX23


2 Answers

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);
like image 81
StriplingWarrior Avatar answered Jan 14 '23 03:01

StriplingWarrior


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");
like image 26
Robin Avatar answered Jan 14 '23 05:01

Robin