java hashmap containskey code example

Example 1: check if map contains key java

if (map.containsKey(key)) {
       // Okay, there's a key but the value is null
    } else {
       // Definitely no such key
    }

Example 2: TreeMap containsKey() method in java

map Integer values to String Keys
import java.util.TreeMap;
public class TreeMapContainsKeyMethodExample
{
   public static void main(String[] args)
   {
      TreeMap<String, Integer> tm = new TreeMap<String, Integer>();
      // Mapping Integer values to string keys
      tm.put("violet", 18);
      tm.put("red", 12);
      tm.put("violet", 14);
      tm.put("green", 16);
      tm.put("blue", 20);
      System.out.println("Given TreeMap Mappings are: " + tm);
      // check for key element 'green'
      System.out.println("Is key 'green' present? " + tm.containsKey("green"));
      // checking for key element 'yellow'
      System.out.println("Is key 'yellow' present? " + tm.containsKey("yellow"));
   }
}

Tags:

Java Example