Map<String, String> num = new HashMap<>();
num.put("one", "first");
if (num.containsKey("one")) {
System.out.println(num.get("one")); // => first
}
For maps, one has to be carrefull not to confuse "containing a key" with "having a value". For example, HashMap
s 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