我正在学习java中的Maps接口(interface),你能在同一个键上引用不同的值吗?我的任务是构建一个字典程序,该程序可以读取小说文本文件和字典。小说作为一个段落阅读,然后解析为单独的单词/字符串,以便可以在字典中搜索它们的拼写。我们的第一个任务是使用集合界面来完成此操作,现在我必须使用 map 并引用带有拼写错误的单词(键)的段落(值)。如果我有拼写错误的单词,它只会引用单个段落,并且我不知道如何将它引用到多个值。
public void spellCheck() {
long startTime = System.currentTimeMillis();
for (String singleParagraph : book.wordCollection) {
String[] arrayWords = singleParagraph.split("[^a-zA-Z_0-9']+");
for (String word : arrayWords) {
if (useOptionalDict) {
if ((dictionary.wordCollection.contains(word) != true)
&& (word.isEmpty() != true)
&& (optionalDictionary.wordCollection
.contains(word) != true)) {
misspelledWord.put(word, singleParagraph);
}// end if
}// end if
else {
if ((dictionary.wordCollection.contains(word) != true)
&& (word.isEmpty() != true)) {
misspelledWord.put(word, singleParagraph);
}// end if
}// end else
}// end enhanced for
}// end enhanced for loop
double elapseTime = (double) (System.currentTimeMillis() - startTime) / 1000.0;
System.out
.printf("\nTotal time to spell check %s: %f\nTotal mispelled words: %d\n",
book.getFileName(), elapseTime, misspelledWord.size());
}// end spellCheck()
最佳答案
在 Java 中不可能将多个值映射到同一个键。不过,您可以创建自定义 map 来执行此操作。
Map<K, List<V>> map = new HashMap <K, ArrayList<V>>:
where K => key type
v => Value type
现在您可以编写如下代码:
插入:首先检查 key 是否存在于 map 中。如果存在,则提取该键对应的列表并将该元素添加到列表中。否则,您需要初始化一个新的 ArrayList,然后向其中添加值,然后将 ArrayList 插入到 Map 中。
正如您所观察到的,这是很多样板代码,如果您在编码生涯中再次需要这样的数据结构,这些代码将被重复。因此,聪明的人拥有开发库,您可以使用它们将多个值映射到单个键。 Multimap就是这样一种数据结构。您可以从 Google Guava 库 Link 查看 MultiMap
关于java - 学习java中的Maps接口(interface),你能在同一个键上引用不同的值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22085129/