实现HashMap时如何为每个键给出不同的数组列表<integer,arraylist <string =“”>&gt;

时间:2015-06-06 18:43:40

标签: java dictionary arraylist hashmap multimap

当我使用HashMap&gt;时,我想为每个键设置不同的数组列表。我想将句子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++
          }

我使用multimap执行此任务。它工作正常。但是我需要用数组列表来实现哈希映射,因为我需要跟踪句子中的单词索引+句号。

当我打印出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

我将对句子的某些块进行一些处理,因此当我想重构句子时,根据索引号将块添加到数组列表中会很容易。
任何帮助都是值得赞赏的。

1 个答案:

答案 0 :(得分:1)

你需要替换它:

MapSentences.put(WordIndex, arraylist);

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

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

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