In this example, you wull see how to search a value and key of element in HashMap.
Search a value and key of element in HashMap.
In this example, you will see how to search element in HashMap. And how to search key in HashMap.
containsKey()-- Returns true if key value present in HashMap
otherwise returns false.
containsValue()-- Returns true if value present in HashMap
otherwise returns false.
SearchKeyOrValue.java
import java.util.HashMap; public class SearchKeyOrValue { public static void main(String[] args) { // create two Interger array for key and value Integer[] intKey = { 2, 4, 6, 3, 1 }; Integer[] intValues = { 45, 24, 67, 38, 91 }; // create an empty hash map HashMapOutput:obHashMap = new HashMap (); for (int i = 0; i < intValues.length; i++) { obHashMap.put(intKey[i], intValues[i]); } System.out.println("Display entry of HashMap.."); System.out.println(obHashMap); Integer value = new Integer(67); Integer key = new Integer(47); // containsValue method search an element in HashMap if (obHashMap.containsValue(value)) { System.out.println("Present : " + value); } else { System.out.println("Not present : " + value); } // containsKey method search a key in HashMap if (obHashMap.containsKey(key)) { System.out.println("Key Present : " + key); } else { System.out.println("Key not present : " + key); } } }
Display entry of HashMap..
{1=91, 2=45, 3=38, 4=24, 6=67} Present : 67 Key not present : 47 |
[ 0 ] Comments