What is the easiest way to obtain a Map Entry?
Created May 8, 2012
Brandon Rohlfs
The easiest way to obtain a Map Entry or (key-value pair) is by invoking the following method provided by the Map interface.
Set<Map.Entry<K,V>> entrySet();
The entrySet() method returns a Set which is populated with Map.Entry objects. The only way to obtain a reference to a Map.Entry is by using an Iterator on the returned Set view. Once a reference to a Map.Entry is obtained the follow methods can be invoked which return the key and value corresponding to the entry.
K getKey() V getValue()
import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.Iterator; public class Emps{ public static void main(String[] args){ Map<String,String> empmap = new TreeMap<String,String>(); empmap.put("956544","Bob Jones"); empmap.put("132485","Phil Harris"); empmap.put("102161","Kamal Uganda"); empmap.put("226545","Bill Russel"); empmap.put("116423","Dorris Smith"); Set s = empmap.entrySet(); for(Iterator i = s.iterator();i.hasNext();){ Map.Entry me = (Map.Entry)i.next(); System.out.println(me.getKey() + " : " + me.getValue()); } } }