Question 19
Back to Exercise
What is the output of the following Java program?
import java.util.Map;
import java.util.TreeMap;
public class Main {
public static void main(String[] args) {
Map<String, Map<String, Integer>> marks = new TreeMap<>();
String[][] data = {{"Asha", "Maths", "91"}, {"Ravi", "Maths", "67"}, {"Asha", "Physics", "84"}, {"Ravi", "Physics", "72"}, {"Asha", "Maths", "95"}};
for (String[] d : data) marks.computeIfAbsent(d[0], k -> new TreeMap<>()).merge(d[1], Integer.parseInt(d[2]), Math::max);
System.out.println(marks + " " + marks.get("Asha").get("Maths"));
}
}
- A {Asha={Maths=95, Physics=84}, Ravi={Maths=67, Physics=72}} 95 Correct
- B {Asha={Maths=91, Physics=84}, Ravi={Maths=67, Physics=72}} 91
- C {Asha={Maths=186, Physics=84}, Ravi={Maths=67, Physics=72}} 186
- D {Ravi={Maths=67, Physics=72}, Asha={Maths=95, Physics=84}} 95
Correct Answer: Option A
merge with Math::max keeps the best score per subject.
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!