Check if key exists, Add an element and Clear the map


Check if key exists

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

Add an element

  • 1. Addition
  • Map<Integer, String> map = new HashMap<>();
    map.put(1, "First element.");
    System.out.println(map.get(1));

    Output : First element

  • 2. Override
  • Map<Integer, String> map = new HashMap<>();
    map.put(1, "First element.");
    map.put(1, "New element.");
    System.out.println(map.get(1));

    Output : New element.

HashMap is used as an example. Other implementations that implement the Map interface may be used as well.


Clear the map

Map<Integer, String> map = new HashMap<>();
 
map.put(1, "First element.");
map.put(2, "Second element.");
map.put(3, "Third element.");
 
map.clear();
 
System.out.println(map.size()); // => 0

Use custom object as key

Before using your own object as key you must override hashCode() and equals() method of your object.

In simple case you would have something like:

class CustomKey {
 private String identifier;
 CustomKey(String identifier) {
     this.identifier = identifier;
 }
 @Override
 public boolean equals(Object obj) { 
     if(obj instanceof CustomKey) {
         return this.identifier.equals(((CustomKey)obj).identifier);
     }
     return false;
 }
 
 @Override
 public int hashCode() {
    return this.identifier.hashCode();
 }
}

hashCode will decide which hash bucket the key belongs to and equals will decide which object inside that hash bucket.

Without these method, the reference of your object will be used for above comparison which will not work unless you use the same object reference every time.

Basic Programs