LearnFrenzy
Sign in Take a free test

HashMap and TreeMap · Predict the Output · Question 17

Inverting a map with duplicate values Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 17 Back to Exercise

What is the output of the following Java program?

Main.java
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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links