Using entrySet()
public void iterateUsingEntrySet(Map<String, Integer> map) {
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + ":" + entry.getValue());
}
}
Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Integer> entry = iterator.next();
System.out.println(entry.getKey() + ":" + entry.getValue());
}
Using keySet()
public void iterateUsingKeySetAndForeach(Map<String, Integer> map) {
for (String key : map.keySet()) {
System.out.println(key + ":" + map.get(key));
}
}
Iterator<String> iterator = map.keySet().iterator();
while (iterator.hasNext()) {
String key = iterator.next();
System.out.println(key + ":" + map.get(key));
}
Using values()
public void iterateValues(Map<String, Integer> map) {
for (Integer value : map.values()) {
System.out.println(value);
}
}
Iterator<Integer> iterator = map.values().iterator();
while (iterator.hasNext()) {
Integer value = iterator.next();
System.out.println("value :" + value);
}
Using forEach() and Lambda
map.forEach((k, v) -> System.out.println((k + ":" + v)));
map.keySet().foreach(k -> System.out.println((k + ":" + map.get(k))));
map.values().forEach(v -> System.out.println(("value: " + v)));
Using Stream API
map.entrySet().stream()
// ... some other Stream processings
.forEach(e -> System.out.println(e.getKey() + ":" + e.getValue()));