LearnFrenzy
Sign in Take a free test

HashMap and TreeMap · Predict the Output · Question 11

Grouping names by first letter Answer, explanation & discussion

  • Output
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 11 Back to Exercise

What is the output of the following Java program?

Main.java
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class Main {
    public static void main(String[] args) {
        Map<Character, List<String>> groups = new TreeMap<>();
        for (String n : List.of("Ravi", "Asha", "Rohit", "Meena", "Arjun", "Riya")) {
            groups.computeIfAbsent(n.charAt(0), k -> new ArrayList<>()).add(n);
        }
        System.out.println(groups + " " + groups.get('R').size());
    }
}
  • A {A=[Asha, Arjun], M=[Meena], R=[Ravi, Rohit, Riya]} 3 Correct
  • B {R=[Ravi, Rohit, Riya], A=[Asha, Arjun], M=[Meena]} 3
  • C {A=[Arjun, Asha], M=[Meena], R=[Ravi, Riya, Rohit]} 3
  • D {A=[Arjun], M=[Meena], R=[Riya]} 1
Correct Answer: Option A

Keys are sorted; each list keeps names in the order they were added.

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