Search code examples
javadictionaryarraylisthashmapmultimap

How to give different array list for each key when implementing HashMap<Integer, ArrayList<String>>


I want to have a different array list for each key when I use HashMap>. I would like to store the sentence id as a key and words of the sentence in array list. To do that I did the following:

//I used the multimap for this task and it works fine.
Multimap<Integer, String> multiMap = ArrayListMultimap.create();
/////
HashMap<Integer, ArrayList<String>> MapSentences = new HashMap<Integer,    ArrayList<String>>();
ArrayList<String> arraylist = new ArrayList<String>();
WordIndex++; 

    while ((line4 = br4.readLine()) != null) {
        String[] splitStr = line4.split("\\s+");
        for(String s : splitStr){
            multiMap.put(WordIndex, s);
            MapSentences.put(WordIndex, arraylist);    
             }
           WordIndex++
          }

I used the multimap for this task. it works fine. But I need to implement the hash map with array list because I need to keep track of the word index in the sentence + the sentence number.

When I printed out content of the hashmap, I noticed the 4 sentences I'm using as a sample had been save as following:

  Key:0 >>> sent1   sent2   sent3  sent4
  Key:1 >>> sent1   sent2   sent3  sent4
  Key:2 >>> sent1   sent2   sent3  sent4
  Key:3 >>> sent1   sent2   sent3  sent4

it should be as following:

  Key:0 >>> sent0
  Key:1 >>> sent1
  Key:2 >>> sent2
  Key:3 >>> sent3

I will do some processing to some chunks of the sentence, so it will be easy to just add chunk to array list based on the index number when I want to reconstruct the sentence.
Any help is appreciative.


Solution

  • You need to replace this:

    MapSentences.put(WordIndex, arraylist);
    

    With lazy creation of array lists for each key:

    ArrayList<?> list = MapSentences.get(WordIndex);
    if (list = null) {
        list = new ArrayList<?>();
    }
    
    list.add(s);
    MapSentences.put(wordIndex, list);