简体   繁体   English

如何在HashMap中找到相同的键和值

[英]How to find same keys and values in HashMap

I have an HashMap with names(key) and dates(value) and I need to show if a name that i enter again is a duplicate (I am doing socket programming with different states).我有一个带有名称(键)和日期(值)的 HashMap,我需要显示我再次输入的名称是否重复(我正在使用不同状态进行套接字编程)。 Example, I put in the map 3 different names and at the forth time I put a duplicate name.例如,我在地图中输入了 3 个不同的名称,第四次输入了一个重复名称。

I tried these codes (they run) but with no success:我尝试了这些代码(它们运行)但没有成功:

HashMap<String, String> map = new HashMap<String, String>();

if(stat.equals("RECEIVE_NAME")){
   name = reader.readLine();
   if(map.containsKey(name)){
      System.out.println("duplicate");
   }
}

or或者

for(Map.Entry<String, String> entry : map.entrySet()){
   if(name.equals(entry.getKey())){
      sendMessage("duplicate");
   }
}

NB: I have a map.put(name) when is not a duplicate after this sequence of blocks.注意:在这一系列块之后,我有一个 map.put(name) when 不是重复的。 And i know that an hash map can not have duplicate keys :)而且我知道哈希映射不能有重复的键:)

A HashMap cannot contain duplicate keys. HashMap 不能包含重复的键。 If you put a key-value pair in a map which already contains the key, the old value will be replaced by the new value.如果将键值对放在已经包含键的映射中,旧值将被新值替换。

map.put() returns the previous value associated with key, or null if there was no mapping for key. map.put()返回与 key 关联的前一个值,如果没有 key 的映射,则返回 null。 So you can store that return value and check if is not null:因此,您可以存储该返回值并检查是否为空:

String check = map.put(name);
if(check != null){
    System.out.println("dup: " + check);
}

Use map.putIfAbsent(name) to not overwrite the associated value.使用map.putIfAbsent(name)不覆盖关联的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM