Java 8 forEach loop

import java.util.HashMap;
import java.util.Map;

public class MapForEach {

public static void main(String[] args) {
Map<Integer, String> map = new HashMap<>();
map.put(1, “B”);
map.put(3, “A”);
map.put(4, “C”);
map.put(2, “D”);
map.put(6, “K”);
map.put(9, “L”);
map.put(8, “M”);
//java 8
map.forEach((k, v) -> System.out.println(“Key : ” + k + ” Value : ” + v));

//check value K exist or not
map.forEach((k, v) -> {
if (“K”.equals(v)) {
System.out.println(v+” is present!”);
}
});

//check key 8 exist or not
map.forEach((k, v) -> {
if (8==k) {
System.out.println(k+” is present!”);
}
});
}

}

Output:

Key : 1 Value : B
Key : 2 Value : D
Key : 3 Value : A
Key : 4 Value : C
Key : 6 Value : K
Key : 8 Value : M
Key : 9 Value : L
K is present!
8 is present!

Leave a comment