Java Language Maps Check if key exists

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!


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

For maps, one has to be carrefull not to confuse "containing a key" with "having a value". For example, HashMaps can contain null which means the following is perfectly normal behavior :

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 

More formally, there is no guarantee that map.contains(key) <=> map.get(key)!=null

Got any Java Language Question?