Master Student Geographic Aggregation in Java with Nested Maps
This article explains how to solve the Student Geographic Information Report problem by defining a Student class, using three‑level nested Java Maps for province‑city‑district grouping, and implementing aggregation and ranking logic to count students per region and identify the city with the most students.
Problem: Student Geographic Information Report
The task is to group a list of students by province, city, and district, then produce statistics such as the number of students per province, the city with the most students, and similar aggregations.
Define a simple Student class with fields for name, province, city, and district.
public class Student {
String name;
String province;
String city;
String district;
public Student(String name, String province, String city, String district) {
this.name = name;
this.province = province;
this.city = city;
this.district = district;
}
}Use a three‑level nested Map<String, Map<String, Map<String, List<Student>>>> to store the hierarchy.
Map<String, Map<String, Map<String, List<Student>>>> geoMap = new HashMap<>();
for (Student s : students) {
geoMap.computeIfAbsent(s.province, k -> new HashMap<>())
.computeIfAbsent(s.city, k -> new HashMap<>())
.computeIfAbsent(s.district, k -> new ArrayList<>())
.add(s);
}Example statistic: count students per province.
for (Map.Entry<String, Map<String, Map<String, List<Student>>>> provinceEntry : geoMap.entrySet()) {
int total = 0;
for (Map<String, List<Student>> cityMap : provinceEntry.getValue().values()) {
for (List<Student> districtList : cityMap.values()) {
total += districtList.size();
}
}
System.out.println(provinceEntry.getKey() + " 省学生总数:" + total);
}Find the city with the most students.
String maxCity = "";
int maxCount = 0;
for (Map<String, Map<String, List<Student>>> cityMap : geoMap.values()) {
for (Map.Entry<String, Map<String, List<Student>>> cityEntry : cityMap.entrySet()) {
int count = 0;
for (List<Student> districtList : cityEntry.getValue().values()) {
count += districtList.size();
}
if (count > maxCount) {
maxCount = count;
maxCity = cityEntry.getKey();
}
}
}
System.out.println("学生最多的城市是:" + maxCity + ",人数:" + maxCount);The same pattern can be applied to real‑world scenarios such as order statistics for delivery services, sales distribution for e‑commerce, or enrollment analysis for education systems.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
IT Services Circle
Delivering cutting-edge internet insights and practical learning resources. We're a passionate and principled IT media platform.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
