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>
Most Recent java Faqs
- How to uncompress a file in the gzip format?
- How to make a gzip file in Java?
- How to use Java String.split method to split a string by dot?
- How to validate URL in Java?
- How to schedule a job in Java?
- How to return the content in the correct encoding from a servlet?
- What is the difference between JDK and JRE?
Most Viewed java Faqs
- How to read input from console (keyboard) in Java?
- How to use HttpURLConnection POST data to web server?
- How to add BASIC Authentication into HttpURLConnection?
- How to Retrieve Multiple Result Sets from a Stored Procedure in JDBC?
- What are class variables in Java?
- What are local variables in Java?
- How to Use Updatable ResultSet in JDBC?