How to Check If a HashMap Contains a Specified Key in Java


In this example we will show how to check if a HashMap contains a specified key in Java.

Codes

package com.beginner.examples;

import java.util.HashMap;

public class KeyInHashMap {

  public static void main(String[] args) {
    // Create a HashMap
    HashMap maps = new HashMap();
    maps.put("a", "1");
    maps.put("b", "2");

    boolean b = maps.containsKey("b"); // check if a HashMap contains a specified key
    System.out.println(b);
  }
}

Output:

true

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments