CODE
import java.util.*;
class MapEntryTest
{
public static void main(String arg[])
{
HashMap<String, Double> hm = new HashMap<String, Double>();
hm.put("Santosh", new Double(3020.55));
hm.put("Ram", new Double(2550.22));
hm.put("Nishan", new Double(2060.66));
hm.put("Amar", new Double(1890.88));
hm.put("Om", new Double(1650.11));
System.out.println("After initializing : " + hm);
Set set = hm.entrySet(); // Setting entry set
Iterator i = set.iterator(); // Iterating to set
while (i.hasNext()) {
// Assigning iterator to map entry
Map.Entry m = (Map.Entry) i.next();
if (m.getKey().equals("Ram")) {
m.setValue(3550.33); // Set value for Ram key
}
// Getting key and value from map entry
System.out.println(m.getKey() + " : " + m.getValue());
}
System.out.println("After changing : " + hm);
}
}
After initializing : {Om=1650.11, Amar=1890.88, Nishan=2060.66, Santosh=3020.55, Ram=2550.22}
Om : 1650.11
Amar : 1890.88
Nishan : 2060.66
Santosh : 3020.55
Ram : 3550.33
After changing : {Om=1650.11, Amar=1890.88, Nishan=2060.66, Santosh=3020.55, Ram=3550.33}
In this program, a HashMap
of key type as String
and value type as Double
is taken which stores elements randomly. Five elements are added to the hash map, then entry set is assigned to set, set is assigned to iterator, and the iterator elements are assigned to map entry to retrieve the key and value.
Prakash
and 4500.45
into hash map by using put method.equals
method give Amar
and set value to 1500.60
.Hashmap
with key type as String
i.e. subjects and value type as Integer
i.e. marks, add the marks to subjects and operate getKey, setKey
and getValue
methods.