.containsKey()
Published Jan 8, 2024
Contribute to Docs
The .containsKey()
method is declared in the Map
interface and is implemented in the HashMap
class. It is used to determine if a Map
object contains a specific key. The function returns a boolean value true
if the key exists, and false
if not.
Syntax
The .containsKey()
method can be called on a HashMap
instance and it requires one parameter, the key that needs to be checked:
hashMap.containsKey(key);
key
: This can take on the form of any type ofObject
.
Example
In the example below, the .containsKey()
method is used to check for the presence of the keys Apples
and Bananas
within a HashMap
:
import java.util.HashMap;public class Groceries {public static void main(String[] args) {// creating a new HashMap which maps string keys to integer valuesHashMap<String, Integer> basket = new HashMap<String, Integer>();// adding fruits to the basketbasket.put("Apples", 50);basket.put("Oranges", 30);// check if "Apples" is a keySystem.out.println("Basket contains Apples: " + basket.containsKey("Apples"));// check if "Bananas is a keySystem.out.println("Basket contains Bananas: " + basket.containsKey("Bananas"));}}
The above example will give the following output:
Basket contains Apples: trueBasket contains Bananas: false
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Java on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn Java
Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.Beginner Friendly16 hours