Menu
Topics Index
...
`


Collections Framework > Map Interfaces >
Siva Nookala - 20 Feb 2017
The Map.Entry interface enables you to work with a map entry.

The entrySet() method declared by the Map returns a Set containing the map entries. Each of these set elements is a Map.Entry object.

Map.Entry Methods :
MethodDescription
boolean equals(Object obj)Compares the specified object with this entry for equality.
Object getKey()Returns the key corresponding to this entry.
Object getValue()Returns the value corresponding to this entry.
int hashCode()Returns the hash code value for this map entry.
Object setValue(Object v)Replaces the value corresponding to this entry with the specified value (optional operation).

Map Entry
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);    
    }
}
OUTPUT

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}

DESCRIPTION

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.

THINGS TO TRY
  • Add Prakash and 4500.45 into hash map by using put method.
  • In equals method give Amar and set value to 1500.60.
  • Create a new 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.

0
Wrong
Score more than 2 points

© meritcampus 2016 - 2017

All Rights Reserved.