java 如何检查地图是否有重复的键?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14554217/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 16:38:23  来源:igfitidea点击:

How to check if a Map has duplicate key?

javamap

提问by None

Ok so here's what I have to do:

好的,这是我必须做的:

Split the passed Listinto individual lines, and then split those lines using a delimiter and then add those parts to a Map.

将传递的内容拆分List为单独的行,然后使用分隔符拆分这些行,然后将这些部分添加到Map.

My code:

我的代码:

public GrammarSolver(List<String> rules) {
    if(rules == null || rules.size() == 0) {
        throw new IllegalArgumentException();
    }
    Map<String, String> rulesMap = new HashMap<String, String>();
    Iterator<String> i = rules.iterator();
    while(i.hasNext()) {
        String rule = i.next(); // store a line from 'rules' List
        String[] parts = rule.split("::="); // split the line into non-terminal and terminal
        rulesMap.put(parts[0], parts[1]); // Put the two parts into the map
    }
    // TODO: exception when duplicate key in map
}

Everything works fine, but now my assignment says that I need to throw an exception if the key of any line is duplicated (occurring more than once).

一切正常,但现在我的作业说如果任何行的键重复(发生多次),我需要抛出异常。

From what I understand, keys can only be unique, so what am I missing here?

据我了解,键只能是唯一的,所以我在这里缺少什么?

回答by Hyman

Keys are unique once added to the HashMap, but you can know if the next one you are going to add is already present by querying the hash map with containsKey(..)or get(..)method.

一旦添加到 中HashMap,键就是唯一的,但是您可以通过使用containsKey(..)get(..)方法查询哈希映射来知道您要添加的下一个键是否已经存在。

回答by cybye

just add the exception to the line

只需将异常添加到该行

rulesMap.put(parts[0], parts[1]); // Put the two parts into the map

like

喜欢

// Put the two parts into the map
if((String existing = rulesMap.put(parts[0], parts[1])) != null) 
      throw new IllegalStateException(
             "duplicated key " + parts[0] 
             + " with value " + existing + " overwritten by " + parts[1]

回答by William Feirie

You can write like below:

你可以像下面这样写:

while(i.hasNext()) {
    String rule = i.next(); // store a line from 'rules' List
    String[] parts = rule.split("::="); // split the line into non-terminal and terminal
    if(rulesMap.containsKey(parts[0]){
        throw New Excpetion(...);
    }else{
        rulesMap.put(parts[0], parts[1]); // Put the two parts into the map
    }

}