The java.util.concurrent.ConcurrentHashMap.containsKey() method is an in-built function in Java which accepts a parameter and checks whether it is a key in this map.
Syntax:
chm.containsKey(Object key_element)
Parameters: The method accepts a single parameter key_element of object type which is to be checked for whether it is a key or not.
Return Value: The method returns true if the specified key_element is a key of this map and false otherwise.
Exception: The function throws NullPointerException when the specified key_element is null.
Below programs illustrate the use of java.util.concurrent.ConcurrentHashMap.containsKey() method :
Program 1: This program involves mapping String Values to Integer Keys.
/* Java Program Demonstrate containsKey() method of ConcurrentHashMap */ import java.util.concurrent.*; class ConcurrentHashMapDemo { public static void main(String[] args) { ConcurrentHashMap<Integer, String> chm = new ConcurrentHashMap<Integer, String>(); chm.put( 100 , "Geeks" ); chm.put( 101 , "for" ); chm.put( 102 , "Geeks" ); // Checking whether 105 is a key of the map if (chm.containsKey( 105 )) { System.out.println( "105 is a key." ); } else { System.out.println( "105 is not a key." ); } // Checking whether 100 is a key of the map if (chm.containsKey( 100 )) { System.out.println( "100 is a key." ); } else { System.out.println( "100 is not a key." ); } } } |
105 is not a key. 100 is a key.
Program 2: This program involves mapping Integer Values to String Keys.
/* Java Program Demonstrate containsKey() method of ConcurrentHashMap */ import java.util.concurrent.*; class ConcurrentHashMapDemo { public static void main(String[] args) { ConcurrentHashMap<String, Integer> chm = new ConcurrentHashMap<String, Integer>(); chm.put( "Geeks" , 120 ); chm.put( "for" , 11 ); chm.put( "GeeksforGeeks" , 15 ); chm.put( "Gfg" , 50 ); chm.put( "GFG" , 25 ); // Checking whether GFG is a key of the map if (chm.containsKey( "GFG" )) { System.out.println( "GFG is a key." ); } else { System.out.println( "GFG is not a key." ); } // Checking whether Geek is a key of the map if (chm.containsKey( "Geek" )) { System.out.println( "Geek is a key." ); } else { System.out.println( "Geek is not a key." ); } } } |
GFG is a key. Geek is not a key.
Reference: https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ConcurrentHashMap.html#containsKey()
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.