Combine collections: a map from each student to the list of their marks.
What to build
A gradebook that records marks and reports averages.
Requirements
- Commands:
mark NAME Madds a mark,drop NAMEremoves that student's lowest mark (printnothing to drop for NAMEif they have no marks),reportprints every student with at least one mark in alphabetical order asNAME: AVG (N marks)with the average to one decimal (1 markfor one), thentop: NAMEfor the highest average (alphabetically first on a tie), orreport: empty.
Input
Line 1: q. Then q commands.
Output
The report lines and failed drops.
Constraints
1 ≤ q ≤ 200; 0 ≤ M ≤ 100.
Example
Input:
6
mark Rina 80
mark Arif 70
mark Rina 90
mark Arif 95
drop Arif
report
Output:
Arif: 95.0 (1 mark)
Rina: 85.0 (2 marks)
top: Arif
Why it works
The map gives each student their own list, computeIfAbsent creates it on first use, and a TreeMap keeps the report in order without sorting.
Examples
Example 1 · Input
6 mark Rina 80 mark Arif 70 mark Rina 90 mark Arif 95 drop Arif report
Expected output
Arif: 95.0 (1 mark) Rina: 85.0 (2 marks) top: Arif
Example 2 · Input
3 drop Zoya report mark Zoya 50
Expected output
nothing to drop for Zoya report: empty
Hints
Hint 1
Map<String, List<Integer>> with computeIfAbsent(name, k -> new ArrayList<>()) adds a mark.
Hint 2
A TreeMap prints the students in alphabetical order.
Solution
Show one correct solution (try it yourself first)
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int q = Integer.parseInt(in.nextLine().trim());
Map<String, List<Integer>> marks = new TreeMap<>();
for (int i = 0; i < q; i++) {
String[] p = in.nextLine().split(" ");
if (p[0].equals("mark")) {
marks.computeIfAbsent(p[1], k -> new ArrayList<>()).add(Integer.parseInt(p[2]));
} else if (p[0].equals("drop")) {
List<Integer> list = marks.get(p[1]);
if (list == null || list.isEmpty()) System.out.println("nothing to drop for " + p[1]);
else list.remove(Collections.min(list));
} else {
String top = null;
double best = -1;
boolean any = false;
for (Map.Entry<String, List<Integer>> e : marks.entrySet()) {
List<Integer> list = e.getValue();
if (list.isEmpty()) continue;
any = true;
double sum = 0;
for (int m : list) sum += m;
double avg = sum / list.size();
System.out.println(e.getKey() + ": " + String.format("%.1f", avg) + " (" + list.size() + (list.size() == 1 ? " mark)" : " marks)"));
if (avg > best) {
best = avg;
top = e.getKey();
}
}
System.out.println(any ? "top: " + top : "report: empty");
}
}
}
}