Click here to learn more about using the forEach construct with Maps.
Java 11 Certification Practice Questions on forEach
Q1. What is the output?
Map map = Map.of(1, 2, 3, 4); map.keySet().forEach(x -> System.out.print(x));
A. Does not compile
B. Throws Exception
C. Prints 13
D. Prints 1234
Choice C is correct. 1 and 3 are printed.
Map.of() is a helper method to create a map. Using this, we can pass any number of
pairs of keys and values.
The usage is – Map. of (“key1”, “value1”, “key2”, “value2”);
In the given code, 1 and 3 are the keys and hence these will get printed when forEach() is invoked on the keys returned by keySet() method.
For Java 11 Certification Exam Practice Questions, refer http://talks.skilltoz.com/java-11-certification-exam-questions/