java - 将多个值添加到 HashMap 中的一个键

标签 java list methods hashmap

我正在开发一个项目,我将获得两个文件;一个是杂乱的单词,另一个是真实的单词。然后,我需要按字母顺序打印出困惑的单词列表,并在其旁边显示匹配的真实单词。问题是每个困惑的单词可能有多个真实的单词。

例如:

cta猫

ezrba 斑马

psot 帖子停止

我完成了该程序,没有考虑每个困惑单词的多个单词,因此在我的 HashMap 中我必须将 更改为 < String , List < String >> ,但这样做后我遇到了一些错误在 .get 和 .put 方法中。如何为每个困惑的单词的每个键存储多个单词?感谢您的帮助。

我的代码如下:

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/

相关文章:

python - 为什么此数据存储为字符串而不是 float ? (Python)

list - 如何使用 sml 编写函数将 2 元组列表转换为扁平列表?

python - 要列出的命名元组字符串

javascript - 尝试在数组中查找序列长度的问题

java - 如何从 jar 文件动态运行 java 类

java - 关于效率: .filter(Optional::isPresent).map(Optional::get) 不是比 .flatmap(Optional::stream) 更好吗?

java - 在 Eclipse 中使用不同版本加载相同插件两次

java - OpenFire插件: Sending custom message packet

ruby - #inject 和缓慢

java - 如何在这个数组操作的Java程序中定义不同的所需方法?