Java Quiz: Using Maps with forEach

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));
Choices

A. Does not compile
B. Throws Exception
C. Prints 13
D. Prints 1234

Answer

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.

Reference

http://talks.skilltoz.com/using-maps-with-foreach/

For Java 11 Certification Exam Practice Questions, refer http://talks.skilltoz.com/java-11-certification-exam-questions/

Leave a Reply

Your email address will not be published. Required fields are marked *