Check if key exists

suggest change
Map<String, String> num = new HashMap<>();
num.put("one", "first");

if (num.containsKey("one")) {
    System.out.println(num.get("one")); // => first
}

Maps can contain null values

Do not confuse “the key is present” with “the value is non-null”. A HashMap may store a null value, and one null key, so this is normal:

Map<String, String> map = new HashMap<>();
map.put("one", null);
if (map.containsKey("one")) {
    System.out.println("This prints !"); // This line is reached 
}
if (map.get("one") != null) {
    System.out.println("This is never reached !"); // This line is never reached 
}

Map has no contains method. containsKey(key) is not the same test as get(key) != null when null values are allowed. ConcurrentHashMap rejects null keys and values.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents