A Map
- cannot contain duplicate keys
- each key can map to at most one value
The following example explains how to iterate through a Map
in various Java versions including Java 8.
package com.smoothexample.java.set;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class MapExample {
public static void main(String[] args) {
Map<String, String> map = new HashMap<String, String>();
populateValues(map);
System.out.println("----------------------------------------------------------------------");
System.out.println("Using Map.Entry");
System.out.println("----------------------------------------------------------------------");
Set<Map.Entry<String, String>> entrySet = map.entrySet();
for (Map.Entry<String, String> mapEntry : entrySet) {
System.out.print(" key = " + mapEntry.getKey());
System.out.println(" value = " + mapEntry.getValue());
}
System.out.println("----------------------------------------------------------------------");
System.out.println("Using iterating through key, using Set");
System.out.println("----------------------------------------------------------------------");
Set<String> keys = map.keySet();
for (String key : keys) {
System.out.print("key = " + key);
System.out.println("value = " + map.get(key));
}
System.out.println("----------------------------------------------------------------------");
System.out.println("Using Java 8");
System.out.println("----------------------------------------------------------------------");
map.forEach((key, value) ->
System.out.println("key = " + key + " value = " + value));
System.out.println("----------------------------------------------------------------------");
System.out.println("Using Java 8, multiple statements in forEach");
System.out.println("----------------------------------------------------------------------");
map.forEach((key, value) -> {
System.out.print("key = " + key);
System.out.println(" value = " + value);
});
}
private static void populateValues(Map<String, String> map) {
for (int i = 1; i <= 10; i++) {
String s = "name" + i;
map.put(String.valueOf(i), s);
}
}
}
Sample output