简体   繁体   中英

How to get the number of occurrences of a key in HashMap?

I am have the Hashmap like this,

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

Now I have added the keys/values like this,

epnSource.put("10.3.2.227","EPN1");
epnSource.put("10.3.2.227","EPN2");
epnSource.put("10.3.2.166","EPN3");
epnSource.put("10.3.2.166","EPN4");
epnSource.put("10.3.2.161","EPN5");

I am trying to do every time before adding a value, I want to check number of occurrences of a key present in the HashMap. Suppose if key 10.3.2.227 has more than two occurrences I shouldn't added it and go for new one. Any suggestions will be helpful.

Suppose if value 10.3.2.227 has more than two occurrences ...

It won't. The way that you have implemented it, the "10.3.2.227" is a key of the Map, and a given key cannot appear more than once in a Map.

If you want a given key (eg "10.3.2.227") to map to multiple values (eg "EPN1" and "EPN1"), you need to use either a Map<String,Set<String>> or a MultiMap class from the Apache or Google/Guava collections libraries.

If the map previously contained a mapping for the key, the old value is replaced.

It is not possible duplicate key in HashMap.

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