Group and summarise records with stream collectors.
What to build
A report of headcount, average salary and best-paid employee per department.
Requirements
- Read n lines
NAME DEPT SALARYinto records. For each department in alphabetical order printDEPT: N people, average A, top NAME(average to one decimal; the top earner, alphabetically first on a tie). - Finally print
highest: NAME (SALARY)for the best-paid employee overall (alphabetically first on a tie).
Input
Line 1: n. Then n employees.
Output
One line per department, then the highest line.
Constraints
1 ≤ n ≤ 100; salaries are whole numbers.
Example
Input:
4
Rina IT 5000
Arif HR 3000
Zoya IT 6000
Omar HR 3500
Output:
HR: 2 people, average 3250.0, top Omar
IT: 2 people, average 5500.0, top Zoya
highest: Zoya (6000)
Why it works
groupingBy builds the departments, collectors count and average each group, and a comparator with a name tie-break picks the top earner the same way in each group and overall.
Examples
Example 1 · Input
4 Rina IT 5000 Arif HR 3000 Zoya IT 6000 Omar HR 3500
Expected output
HR: 2 people, average 3250.0, top Omar IT: 2 people, average 5500.0, top Zoya highest: Zoya (6000)
Example 2 · Input
1 Solo Ops 100
Expected output
Ops: 1 people, average 100.0, top Solo highest: Solo (100)
Hints
Hint 1
record Employee(String name, String dept, int salary), then groupingBy(Employee::dept, TreeMap::new, ...).
Hint 2
averagingInt gives a Double; format it with %.1f.
Solution
Show one correct solution (try it yourself first)
import java.util.*;
import java.util.stream.*;
public class Main {
record Employee(String name, String dept, int salary) {}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = Integer.parseInt(in.nextLine().trim());
List<Employee> staff = new ArrayList<>();
for (int i = 0; i < n; i++) {
String[] p = in.nextLine().split(" ");
staff.add(new Employee(p[0], p[1], Integer.parseInt(p[2])));
}
Comparator<Employee> bestFirst = Comparator.comparingInt(Employee::salary).reversed().thenComparing(Employee::name);
Map<String, List<Employee>> byDept = staff.stream().collect(Collectors.groupingBy(Employee::dept, TreeMap::new, Collectors.toList()));
for (Map.Entry<String, List<Employee>> e : byDept.entrySet()) {
List<Employee> people = e.getValue();
double avg = people.stream().mapToInt(Employee::salary).average().orElse(0);
Employee top = people.stream().sorted(bestFirst).findFirst().get();
System.out.println(e.getKey() + ": " + people.size() + " people, average " + String.format("%.1f", avg) + ", top " + top.name());
}
Employee best = staff.stream().sorted(bestFirst).findFirst().get();
System.out.println("highest: " + best.name() + " (" + best.salary() + ")");
}
}