The Java Map interface, unlike other interfaces, does not implement the Iterable interface. Consequently, a Map cannot be navigated using a for-each style for loop or an iterator. Despite this, a solution exists in the form of a collection-view of the Map. This alternative allows the utilization of either a for loop or an iterator for cycling through the Map.
While learning how to iterate over a Map in Java is essential for effective data manipulation, it’s also valuable to understand Java abstract class variables, as they play a crucial role in the broader landscape of Java programming.
The Map.Entry interface is generic and is declared as follows:
interface Map.Entry<K, V>
In this declaration, K specifies the type of keys, and V specifies the type of values. This feature provides strong typing support for keys and values when working with map entries in Java.
Method | Description |
---|---|
entrySet() | Returns a Set of map entries (objects of type Map.Entry). |
keySet() | Returns a Set of keys from the map. |
values() | Returns a Collection of values from the map. |
Method | Description |
---|---|
getKey() | Returns the key for entry. |
getValue() | Returns the entry’s value. |
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
public class MapIterationDemo {
public static void main(String[] args) {
TreeMap map = new TreeMap();
map.put(new Integer(103), "CCC");
map.put(new Integer(105), "EEE");
map.put(new Integer(102), "BBB");
map.put(new Integer(101), "AAA");
map.put(new Integer(104), "DDD");
// Iterate using key
Set s = map.keySet();
Iterator itr = s.iterator();
while (itr.hasNext()) {
Integer k = (Integer) itr.next();
System.out.println(k);
// using key can get value
String v = (String) map.get(k);
System.out.print(k + "\t" + v + "\n");
}
// Iterate using values
Collection c = map.values();
Iterator itr1 = c.iterator();
while (itr1.hasNext()) {
String name = (String) itr1.next();
System.out.println(name);
}
// iterate using both key and value
Set s1 = map.entrySet();
Iterator itr2 = s1.iterator();
while (itr2.hasNext()) {
Map.Entry me = (Map.Entry) itr2.next();
Integer k = (Integer) me.getKey();
String v = me.getValue().toString();
System.out.print(k + "\t" + v + "\n");
}
}
}
Output:
101
101 AAA
102
102 BBB
103
103 CCC
104
104 DDD
105
105 EEE
AAA
BBB
CCC
DDD
EEE
101 AAA
102 BBB
103 CCC
104 DDD
105 EEE
Iterating through a Map in Java may not be straightforward due to its lack of support for the Iterable interface. However, with the understanding of the Map.Entry interface and the collection-view of a Map, you can effectively iterate through the Map using keySet(), values(), and entrySet() methods. Equipped with this knowledge and the example in this guide, you can confidently deal with any Map iteration tasks in Java.