Question 17
Back to Exercise
What is the output of the following Java program?
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeMap;
public class Main {
public static void main(String[] args) {
Map<String, String> capitalOf = new LinkedHashMap<>();
capitalOf.put("MH", "Mumbai"); capitalOf.put("KA", "Bengaluru"); capitalOf.put("XX", "Mumbai");
Map<String, String> stateOf = new TreeMap<>();
capitalOf.forEach((state, city) -> stateOf.put(city, state));
System.out.println(stateOf);
}
}
- A {Bengaluru=KA, Mumbai=XX} Correct
- B {Bengaluru=KA, Mumbai=MH}
- C {Mumbai=MH, Bengaluru=KA, Mumbai=XX}
- D {KA=Bengaluru, MH=Mumbai}
Correct Answer: Option A
Duplicate values become duplicate keys in the inverted map, so the later put wins.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!