Is there any difference between these two statements when I just want to set an 'if' statement?
// it is a HashMap
if (map.keySet().contains(myKey)) { //do something...}
if (map.containsKey(myKey)){ //do the same thing...}
get(Object) does explicitly warn about the subtle differences between Map. get(Object) and Map. containsKey(Object) : If this map permits null values, then a return value of null does not necessarily indicate that the map contains no mapping for the key; it's also possible that the map explicitly maps the key to null .
The keySet() method is used to get a Set view of the keys contained in this map.
util. Map. containsKey() method is used to check whether a particular key is being mapped into the Map or not. It takes the key element as a parameter and returns True if that element is mapped in the map.
keySet() method in Java is used to create a set out of the key elements contained in the hash map. It basically returns a set view of the keys or we can create a new set and store the key elements in them.
containsKey()
is faster. keySet()
returns a set backed by the HashMap itself, and its contains()
method calls containsKey()
.
This is its implementation:
public final boolean contains(Object o) { return containsKey(o); }
(http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/java/util/HashMap.java#913)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With