4

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.

DomX23
  • 867
  • 5
  • 13
  • 26
  • You may also want to look into a multimap class from a 3rd party collections library. – Sign Dec 02 '11 at 19:53
  • Note: Use the interfaces as declaration types if possible: Map> fileRank = new HashMap>(); – Puce Dec 02 '11 at 19:58

5 Answers5

5

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);
Sign
  • 1,919
  • 18
  • 33
StriplingWarrior
  • 151,543
  • 27
  • 246
  • 315
3

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");
Robin
  • 36,233
  • 5
  • 47
  • 99
2

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);
Mechkov
  • 4,294
  • 1
  • 17
  • 25
0

private static HashMap> mmArrays = new HashMap>();

mmArrays.put(key,data);

Ayie Shindo
  • 43
  • 1
  • 3
0

A possible solution:

public class MyContainer {

    private final Map<String, List<String>> myMap = new HashMap<String, List<String>>();

    public void add(String key, String value) {
        if(myMap.containsKey(key)) {
            myMap.get(key).add(value);
        } else {
            ArrayList<String> newList = new ArrayList<String>();
            newList.add(value);

            myMap.put(key, newList);
        }
    }
}
ollins
  • 1,851
  • 12
  • 16