Write Java code to group a list of names by their first letter using streams.
Use Collectors.groupingBy with a classifier that returns the first character, and pass TreeMap::new if you want the keys sorted. It makes one pass, so O(n) time and O(n) space.
Explain it simply
Think of sorting a pile of admission forms into pigeonholes labelled A, B, C by the first letter of each student's name. groupingBy builds the pigeonholes and drops each name into the right one.
Line by line
import java.util.*;
import java.util.stream.*;
List<String> names = List.of("Asha", "Arjun", "Bina", "Chetan", "Bhavna");
Map<Character, List<String>> byLetter = names.stream()
.collect(Collectors.groupingBy(
n -> n.charAt(0), // classifier: which pigeonhole
TreeMap::new, // keep the keys sorted
Collectors.toList())); // what to store in each
System.out.println(byLetter);
// prints: {A=[Asha, Arjun], B=[Bina, Bhavna], C=[Chetan]}The classifier returns a Character. Without the TreeMap argument, the default HashMap does not promise key order. To count instead of listing, replace the last argument with Collectors.counting().
Complexity
Time O(n) for grouping (plus O(k log k) for k distinct keys with TreeMap), space O(n).
What to say in the interview
"groupingBy takes a classifier, an optional map factory and a downstream collector. The downstream collector can count, sum, map or join. I would add a check for empty strings, since charAt(0) throws on them."
Common mistakes
- Calling charAt(0) on a name that might be empty or null.