Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between map.keySet().contains() and map.containsKey()

Tags:

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...}
like image 762
Victor Zhu Avatar asked Aug 24 '15 02:08

Victor Zhu


People also ask

What is the significant difference between containsKey () and get ()?

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 .

What is use of keySet () in map?

The keySet() method is used to get a Set view of the keys contained in this map.

What is map containsKey?

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.

What does HashMap keySet mean?

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.


1 Answers

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)

like image 175
Arturo Torres Sánchez Avatar answered Oct 11 '22 16:10

Arturo Torres Sánchez