How to get key and value from HashMap using Map.Entry - Java @ Desk

Friday, May 17, 2013

How to get key and value from HashMap using Map.Entry

Explanation :
A map entry (key-value pair).
1) The Map.entrySet method returns a collection-view of the map, whose elements are of this class.
2) The only way to obtain a reference to a map entry is from the iterator of this collection-view.
3) These Map.Entry objects are valid only for the duration of the iteration; more formally, the behavior of a map entry is undefined if the backing map has been modified after the entry was returned by the iterator, except through the setValue operation on the map entry.


import java.util.HashMap;
import java.util.Map;

public class MapEntryIterator {

    public static void main(String args[]) {

        Map map = new HashMap();
        map.put(10, "Ten");
        map.put(9, "Nine");
        map.put(8, "Eight");
        map.put(7, "Seven");
        map.put(6, "Six");

        for (Map.Entry entry : map.entrySet()) {
            System.out.println("Key : " + entry.getKey());
            System.out.println("Value : " + entry.getValue());
        }
    }
}






No comments:

Post a Comment