Java HashMap: Adding to Arraylist

I am using the HashMap class and it looks like this:

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

I am wondering how to add a new line to an Arraylist after the initial input.

 fileRank.put(word, file1); 

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

+4
source share
5 answers

First you should get a list of arrays:

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

Of course, this becomes more complicated if you still do not know if there is an entry for this key.

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

You are asking for a map for a value for a specific 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"); 
+3
source

Get an ArrayList based on the string key, make add() in ArrayList, and then return it to HashMap (optional, since the map already contains a link to it);

 fileRank.get(word).add(String) fileRank.put(work, list); 
+2
source

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); } } } 
0
source

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

mmArrays.put (key, data);

0
source

Source: https://habr.com/ru/post/1384394/


All Articles