文本文件 100 萬行,每行一條微博,需統計 @用戶名 出現次數最多的前 100 用戶。
@(\\w+) 提取所有 @用戶名。HashMap 累加每個用戶名計數。Key 為用戶名,Value 為出現次數。O(N log N)。O(N log 100),內存只存 100 個元素。BufferedReader),避免一次性載入 100 萬行到內存。int[] 陣列直接映射計數,比 HashMap 更快。Map counter = new HashMap<>();
Pattern pattern = Pattern.compile("@(\\w+)");
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
Matcher m = pattern.matcher(line);
while (m.find()) {
String name = m.group(1);
counter.merge(name, 1, Integer::sum);
}
}
}
// 取 Top 100
List> top = counter.entrySet().stream()
.sorted(Map.Entry.comparingByValue().reversed())
.limit(100).collect(Collectors.toList());