How to loop through a Map?

Using Map in java is a convenient way to store objects into a collection and identified by their names. The Map interface provides API of adding and getting a particular object by the name it’s stored with. However, there is no simple API to loop through all the items in the Map.
An older fashion to do this is to use the java.util.Iterator, for example:
public void test () {
Map testMap = new HashMap();
testMap.put("key1", "value1");
testMap.put("key2", "value2");
Iterator it = testMap.keySet() .iterator () ;
while ( it.hasNext () ) {
String key = (String) it.next () ;
System.out.println ( "key:" + key);
System.out.println ("value:" + testMap.get ( key ) ) ;
}
}
If you want to take advantage of the
for (Type x: collections) {

}
You can by pass the iterator, instead to use the java.util.Map.Entry. The Map.Entry is a name-value pair. The entrySet() method of the Map will return a collection f the the Map.Entry. The following is an example:
public void test () {
Map testMap = new HashMap();
testMap.put("key1", "value1");
testMap.put("key2", "value2");
for (Map.Entry entry: testMap.entrySet()) {
System.out.println ( "key:" + entry.getKey());
System.out.println ("value:" + entry.getValue() ) ;
}
}

The second way is useful if you want to do the looping inside a JSP with tags:
<table>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<c:forEach var="entry" items="${testMap.entrySet()}"
<tr>
<td>${entry.key}</td>
<td>${entry.value}</td>
</tr>
</c:forEach>
</table>

No comments:

Post a Comment