【问题标题】:Adding multiple values to one key in a HashMap将多个值添加到 HashMap 中的一个键
【发布时间】:2016-10-14 22:40:38
【问题描述】:

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

例如:

猫猫

斑马

psot 停止后

我完成了程序,没有考虑每个混乱单词的多个单词,所以在我的 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);
    }  
}

【问题讨论】:

  • 因此,当您想从 Hashmap 编辑或获取值时,请确保您使用 List 作为值和 String 作为键,目前您正在尝试将 String 分配给您获得的内容从 .get() 返回 List 对象类型
  • 当然StringList&lt;String&gt; 不同。你对什么感到困惑?

标签: java list methods hashmap


【解决方案1】:

你可以这样做:

换行:

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

【讨论】:

  • List&lt;String&gt; scrambled = dWordMap.get(createKey(word));放在最上面可以避免额外的查找。
  • 是的,当然..我用 createKey(word); 把它移到了顶部;因为 createKey 被调用了两次。
【解决方案2】:

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

dwordMap 的类型是 HashMap>。所以应该是 List 而不是单词,即字符串。

【讨论】:

    猜你喜欢
    • 2017-10-11
    • 2019-02-19
    • 1970-01-01
    • 1970-01-01
    • 2022-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-16
    相关资源
    最近更新 更多