简体   繁体   中英

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). Example, I put in the map 3 different names and at the forth time I put a duplicate name.

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. And i know that an hash map can not have duplicate keys :)

A HashMap cannot contain duplicate keys. 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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