实现HashMap<Integer, ArrayList<String>>时如何为每个key给出不同的数组列表

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

我想在使用 HashMap 时为每个键设置一个不同的数组列表>。我想将句子 id 作为关键字和句子的单词存储在数组列表中。为此,我执行了以下操作:

//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++
          }

我使用了多图来完成这个任务。它工作正常。但是我需要用数组列表实现哈希映射,因为我需要跟踪句子中的单词索引+句子编号。

当我打印出 hashmap 的内容时,我注意到我用作示例的 4 个句子已保存如下:

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

应该是这样的:

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

我会对句子的一些块做一些处理,所以当我想重构句子时,只需要根据索引号将块添加到数组列表中就很容易了。
任何帮助都是感激的。

你需要替换这个:

MapSentences.put(WordIndex, arraylist);

通过为每个键延迟创建数组列表:

ArrayList<?> list = MapSentences.get(WordIndex);
if (list = null) {
    list = new ArrayList<?>();
}

list.add(s);
MapSentences.put(wordIndex, list);