How to Check If TreeMap contains Particular Key in Java


The example aims to check if TreeMap object contains a particular key with containsKey method.

Source Code

package com.beginner.examples;

import java.util.TreeMap;

public class CheckKeyOfTreeMap {

	public static void main(String[] args) {
		
		//create TreeMap.
		TreeMap treeMap = new TreeMap();
		
		treeMap.put("1","Alice");
		treeMap.put("2","Bob");
		treeMap.put("3","Jack");
		
		/*
		 * To check whether a particular key exists in TreeMap using containsKey method of TreeMap.
		 */
		boolean result = treeMap.containsKey("2");
		System.out.println("2 exists in TreeMap ? : " + result);

	}

}

Output:

2 exists in TreeMap ? : true

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments