Group into Lists
Completed
Read lines department name. Build a TreeMap<String, List<String>> and print each department with its names sorted.
Input
n, then n lines.
Output
One line per department: dept: [names]
Example
Input
5 sales zoe it amy sales bob hr cy it dan
Output
hr: [cy] it: [amy, dan] sales: [bob, zoe]
Editor
Java
Hints
Create the list the first time a department appears.
computeIfAbsent(dept, k -> new ArrayList<>()) is the Java 8 shortcut.
Solution explanation
A map from key to list is the standard way to group data.
Show solution
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
Map<String, List<String>> byDept = new TreeMap<String, List<String>>();
for (int i = 0; i < n; i++) {
String dept = sc.next();
String name = sc.next();
List<String> list = byDept.get(dept);
if (list == null) {
list = new ArrayList<String>();
byDept.put(dept, list);
}
list.add(name);
}
for (Map.Entry<String, List<String>> e : byDept.entrySet()) {
Collections.sort(e.getValue());
System.out.println(e.getKey() + ": " + e.getValue());
}
}
}