我正在开发一个项目,我将获得两个文件;一个是杂乱的单词,另一个是真实的单词。然后,我需要按字母顺序打印出困惑的单词列表,并在其旁边显示匹配的真实单词。问题是每个困惑的单词可能有多个真实的单词。
例如:
cta猫
ezrba 斑马
psot 帖子停止
我完成了该程序,没有考虑每个困惑单词的多个单词,因此在我的 HashMap 中我必须将
我的代码如下:
import java.io.*;
import java.util.*;
public class Project5
{
public static void main (String[] args) throws Exception
{
BufferedReader dictionaryList = new BufferedReader( new FileReader( args[0] ) );
BufferedReader scrambleList = new BufferedReader( new FileReader( args[1] ) );
HashMap<String, List<String>> dWordMap = new HashMap<String, List<String>>();
ArrayList<String> scrambled = new ArrayList<String>();
while (dictionaryList.ready())
{
String word = dictionaryList.readLine();
//throw in an if statement to account for multiple words
dWordMap.put(createKey(word), word);
}
dictionaryList.close();
ArrayList<String> scrambledList = new ArrayList<String>();
while (scrambleList.ready())
{
String scrambledWord = scrambleList.readLine();
scrambledList.add(scrambledWord);
}
scrambleList.close();
Collections.sort(scrambledList);
for (String words : scrambledList)
{
String dictionaryWord = dWordMap.get(createKey(words));
System.out.println(words + " " + dictionaryWord);
}
}
private static String createKey(String word)
{
char[] characterWord = word.toCharArray();
Arrays.sort(characterWord);
return new String(characterWord);
}
}
最佳答案
你可以这样做:
替换行:
dWordMap.put(createKey(word), word);
与:
String key = createKey(word);
List<String> scrambled = dWordMap.get(key);
//make sure that scrambled words list is initialized in the map for the sorted key.
if(scrambled == null){
scrambled = new ArrayList<String>();
dWordMap.put(key, scrambled);
}
//add the word to the list
scrambled.add(word);
关于java - 将多个值添加到 HashMap 中的一个键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40052978/