Victor Zhu
Victor Zhu

Reputation: 241

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

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...}

Upvotes: 21

Views: 12990

Answers (1)

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)

Upvotes: 17

Related Questions