在HashMap中向一个键添加多个值

时间:2016-10-14 22:40:38

标签: java list methods hashmap

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

例如:

cta cat

ezrba斑马

psot post stop

我完成了程序而没有考虑每个混乱单词的多个单词,所以在我的HashMap中我不得不改变<字符串,字符串>到<字符串,列表<字符串> >,但在执行此操作后,我在.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);
    }  
}

2 个答案:

答案 0 :(得分:2)

你可以做点什么:

替换行:

dWordMap.put(createKey(word), word);

with:

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);

答案 1 :(得分:0)

dWordMap.put(createKey(word),word);

dwordMap的类型为HashMap&gt;。所以不是单词,而是字符串,它应该是List。