gpt4 book ai didi

java - 实现 HashMap> 时如何为每个键提供不同的数组列表

转载 作者:行者123 更新时间:2023-11-30 08:08:59 25 4
gpt4 key购买 nike

当我使用 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 ,因为我需要跟踪句子中的单词索引+句子编号。

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

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

最佳答案

您需要替换它:

MapSentences.put(WordIndex, arraylist);

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

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

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

关于java - 实现 HashMap<Integer, ArrayList<String>> 时如何为每个键提供不同的数组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30686375/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com