import java.util.*;
import java.util.stream.*;
public class FileRecordExample {
public static void main(String[] args) {
// Sample data
List<FileRecord> records = Arrays.asList(
new FileRecord("2025", "07", "Taipei"),
new FileRecord("2025", "07", "Kaohsiung"),
new FileRecord("2025", "07", "Taipei"),
new FileRecord("2025", "07", "Tainan"),
new FileRecord("2025", "07", "Taoyuan"),
new FileRecord("2025", "07", "Hsinchu"),
new FileRecord("2025", "07", "Taichung"),
new FileRecord("2025", "06", "Taichung"),
new FileRecord("2025", "06", "Hsinchu")
);
// 1. Group by "yyyyMM" and collect locations into lists
Map<String, List<String>> grouped = records.stream()
.collect(Collectors.groupingBy(
r -> r.getYyyy() + r.getMm(),
Collectors.mapping(FileRecord::getLocation, Collectors.toList())
));
// 2+3. Sort keys descending, and if a list has more than 6 entries, limit to first 6
LinkedHashMap<String, List<String>> result = grouped.entrySet().stream()
// Sort by key (yyyyMM) in reverse (descending) order
.sorted(Map.Entry.<String, List<String>>comparingByKey(Comparator.reverseOrder()))
// Collect into a LinkedHashMap to preserve order
.collect(Collectors.toMap(
Map.Entry::getKey,
entry -> entry.getValue().stream()
.limit(6) // keep at most 6 locations per group
.collect(Collectors.toList()),
(u, v) -> u, // merge function (not used here)
LinkedHashMap::new
));
// Print the final result
result.forEach((yyyymm, locations) ->
System.out.println(yyyymm + " -> " + locations)
);
}
}