How to check if Key or Value exists in a Map ?

DeeKay February 11, 2018 at 2:04 am · java.util

In this tutorial we will see how to check if Key or Value exists in a Map. Map or HashMap is the java collection class which stores data in Key-Value pair. Java collections is a set of classes and interfaces that implement commonly reusable collection data structures.

To check if Key or Value exists in a Map, Map or HashMap class provides two methods boolean containsKey(Object key) and boolean containsValue(Object value).

Below Java code will show you how to check if Key or Value exists in a Map

/**
 * Created on Feb 09, 2018 Copyright(c) https://kodehelp.com All Rights Reserved.
 */
package com.kodehelp.hashmap;

import java.util.HashMap;
import java.util.Map;

/**
 * @author https://kodehelp.com
 *
 */
public class KodehelpMapContainsKeyOrValue {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Map<String, String> studentsMap = new HashMap<>();
		
		studentsMap.put("1", "Jeniffer");
		studentsMap.put("3", "Catlyn");
		studentsMap.put("5", "John");
		studentsMap.put("10", "Aria");
		
		//To check if Key exist, we used containsKey() method of a map
		System.out.println(studentsMap.containsKey("1")?
				"Key (1) exist in HashMap":"Key (1) does not exist in HashMap");
		System.out.println(studentsMap.containsKey("2")?
				"Key (2) exist in HashMap":"Key (2) does not exist in HashMap");
		System.out.println(studentsMap.containsKey("3")?
				"Key (3) exist in HashMap":"Key (3) does not exist in HashMap");
		
		//To check if Value exist, we used containsValue() method of a map
		System.out.println(studentsMap.containsValue("Jeniffer")?
				"Value (Jeniffer) exist in HashMap":"Value (Jeniffer) does not exist in HashMap");
		System.out.println(studentsMap.containsValue("Joy")?
				"Value (Joy) exist in HashMap":"Value (Joy) does not exist in HashMap");
		
	}

}

 
Output:

Key (1) exist in HashMap
Key (2) does not exist in HashMap
Key (3) exist in HashMap
Value (Jeniffer) exist in HashMap
Value (Joy) does not exist in HashMap

Hope you find this tutorial useful. Happy Learning !