In this section, you will see how to get key and value of HashMap in java.
How to get key and value of HashMap in java.
The HashMap extends AbstractMap and implements Map interface. It is available in java.util package. It stores value in the form of key/values pair. The put(key,value) method is used for adding entry in map.
entrySet()-- It is a method of HashMap
class. Returns a Set of entries(Key/Value) of
corresponding map.
getKey()-- It is a method of Map.Entry
interface. Returns key of corresponding entry.
getValue()-- It is a method of Map.Entry
interface. Returns value of corresponding entry.
AccessKeyValueOfHashMap.java
import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; public class AccessKeyValueOfHashMap { public static void main(String[] args) { // Create a Empty HashMap HashMap<String, String> obHashMap = new HashMap<String, String>(); // Put values in hash map obHashMap.put("AB", "1"); obHashMap.put("EF", "2"); obHashMap.put("Gh", "3"); obHashMap.put("CD", "4"); //Store entry (Key/Value)of HashMap in set Set mapSet = (Set) obHashMap.entrySet(); //Create iterator on Set Iterator mapIterator = mapSet.iterator(); System.out.println("Display the key/value of HashMap."); while (mapIterator.hasNext()) { Map.Entry mapEntry = (Map.Entry) mapIterator.next(); // getKey Method of HashMap access a key of map String keyValue = (String) mapEntry.getKey(); //getValue method returns corresponding key's value String value = (String) mapEntry.getValue(); System.out.println("Key : " + keyValue + "= Value : " + value); } } }Output:
Display the key/value of HashMap.
Key : Gh= Value : 3 Key : AB= Value : 1 Key : CD= Value : 4 Key : EF= Value : 2 |
[ 0 ] Comments