Hashmap键不起作用

时间:2013-02-26 07:41:50

标签: java hashmap

我有一个HashMap,其某些键如“crash”和“crashes”会返回相同的响应。我想创建一个新的HashMap,它将同义词映射到responseMap中的唯一键(例如,在同义词Map中将“崩溃”,“崩溃”和“崩溃”映射到“崩溃”)。

 private void fillSynonymMap()
  {
    synonymMap.put("crash", "crash");
    synonymMap.put("crashes", "crash");
    synonymMap.put("crashed", "crash");
  }

我坚持的是如何输入这些键,以便我可以简化下面的代码。

 private void fillResponseMap()
{
    responseMap.put("crash", 
                    "Well, it never crashes on our system. It must have something\n" +
                    "to do with your system. Tell me more about your configuration.");
    responseMap.put("crashes", 
                    "Well, it never crashes on our system. It must have something\n" +
                    "to do with your system. Tell me more about your configuration.");\
   responseMap.put("crashed", 
                    "Well, it never crashes on our system. It must have something\n" +
                    "to do with your system. Tell me more about your configuration.");
}



public String generateResponse(HashSet<String> words)
{
    for (String word : words) {
        String response = responseMap.get(word);
        if(response != null) {
            return response;
        }
    }

    // If we get here, none of the words from the input line was recognized.
    // In this case we pick one of our default responses (what we say when
    // we cannot think of anything else to say...)
    return pickDefaultResponse();
}

2 个答案:

答案 0 :(得分:1)

稍微搞乱后我写了一个函数,在返回默认消息之前会查找同义词。

public String getResponse()
{
    HashMap<String, String> responseMap = new HashMap<String, String>();
    HashMap<String, String> synonymMap = new HashMap<String, String>();

    responseMap.put("crash", "Hello there");
    // Load the response value.
    synonymMap.put("crash", "crash");
    synonymMap.put("crashed", "crash");
    synonymMap.put("crashes", "crash");
    // Load the synonyms.

    String input = "crashed";
    // Select input value.

        if(responseMap.containsKey(input))
        {
            // Response is already mapped to the word.
            return responseMap.get(input);
        }
        else
        {
            // Look for a synonym of the word. 
            String synonym = synonymMap.get(input);
            if(!synonym.equals(input) && responseMap.containsKey(synonym))
            {
                // If a new value has been found that is a key..
                return responseMap.get(synonym);
            }
        }
        // If no response, set default response.
    input = "This is a default response";
    return input;
}

如您所见,该功能首先检查密钥是否存在。如果没有,则尝试使用同义词。如果该同义词没有通过测试,它将移动到底部的默认代码,这将把输入设置为某个默认值并返回该代码:)

答案 1 :(得分:0)

您可以使用第二张地图。

第一张地图将同义词翻译成基本键,而基本键又可用于带答案的第二张地图。

这也允许灵活地扩展同义词而不扩大实际的响应图。

此外,在这种情况下,您实际上可以使用其他类型作为答案地图的键。它必须与同义词映射的值类型相同。

这样,您也可以使用

Map<String, YourEnum> and Map<YourEnum, String> 

使用EnumMap作为Map接口的实现。