java 8 map foreach code example
Example 1: java 8 loop in map
Map items = new HashMap<>();
items.put("A", 10);
items.put("B", 20);
items.put("C", 30);
items.put("D", 40);
items.put("E", 50);
items.put("F", 60);
items.forEach((k,v)->System.out.println("Item : " + k + " Count : " + v));
items.forEach((k,v)->{
System.out.println("Item : " + k + " Count : " + v);
if("E".equals(k)){
System.out.println("Hello E");
}
});
Example 2: java 8 map foreach
public void iterateUsingLambda(Map map) {
map.forEach((k, v) -> System.out.println((k + ":" + v)));
}
Example 3: java 8 map foreach
public void iterateUsingEntrySet(Map map) {
for (Map.Entry entry : map.entrySet()) {
System.out.println(entry.getKey() + ":" + entry.getValue());
}
}
Example 4: java 8 map foreach
public void iterateUsingIteratorAndEntry(Map map) {
Iterator> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry entry = iterator.next();
System.out.println(entry.getKey() + ":" + entry.getValue());
}
}
Example 5: java 8 map foreach
public void iterateUsingStreamAPI(Map map) {
map.entrySet().stream()
// ...
.forEach(e -> System.out.println(e.getKey() + ":" + e.getValue()));
}
Example 6: java 8 hashmap example stackoverflow
Optional o = id1.entrySet()
.stream()
.filter( e -> e.getKey() == 1)
.map(Map.Entry::getValue)
.findFirst();