Using Maps with forEach

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

To know the basics of using the forEach construct in Java, refer this article.

How do we iterate Map keys using forEach?

The keySet() method returns the keys in a map as a Set. Hence, the forEach method can be used to iterate the keys as shown in the below example.

Map<String, String> map = new HashMap<>();
map.put("VegSoup", "Carrot");
map.put("NonVegSoup", "Chicken");
map.keySet().forEach(b -> System.out.println(b));
// Prints 
NonVegSoup
VegSoup

How do we iterate Map values using forEach?

The values() method returns the values in a map as a Set. Hence, the forEach method can be used to iterate the values as shown in the below example.

Map<String, String> flowers = new HashMap<>();
flowers.put("Red", "Rose");
flowers.put("Yellow", "Sunflower");
flowers.values().forEach(b -> System.out.println(b));
// Prints 
Rose
Sunflower

How do we iterate Map entries using forEach?

Even though Maps are not Collections (that means, they are not Iterable), they still support forEach construct by passing a BiConsumer implementation, which allows an action to be performed on the key and value simultaneously as shown in the below example.

Map<String, String> map = new HashMap<String, String>();
map.put("A", "Apple");
map.put("B", "Ball");
map.put("C", "Cat");
map.forEach((k, v) -> System.out.println("Key= " + k + ", Value= " + v));
 
// Output is Key = A, Value = Apple
// Key = B, Value = Ball
// Key = C, Value = Cat

Quiz

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

For the answer, refer http://talks.skilltoz.com/java-quiz-using-maps-with-foreach/

Leave a Reply

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