【发布时间】:2020-08-09 22:26:48
【问题描述】:
我有一个 XML 文件,我需要在其中查找并计算年份标签的出现次数。 例如:
Found year 2020 10 times.
Found year 2017 1 times.
Found year 2019 2 times.
(...)
为了避免重复使用 HashSet 的年份。 代码:
public class Publications {
public static void main(String[] args) throws IOException {
Set<String> publicationYears = new LinkedHashSet<>();
try (BufferedReader reader = Files.newBufferedReader(Paths.get("dblp-2020-04-01.xml"))) {
Pattern pattern = Pattern.compile("<year>(.+?)</year>", Pattern.DOTALL);
for (String line; (line = reader.readLine()) != null; ) {
Matcher matcher = pattern.matcher(line);
if (matcher.find()) {
String year = matcher.group(1);
publicationYears.add(year);
}
}
}
结果:
2010
2002
1992
1994
1993
2006(...)
但现在我找不到有效的代码来计算每年的出现次数。创建一个多维数组然后搜索会很慢。有什么建议吗?
【问题讨论】:
-
您是否想过使用地图来跟踪每年的计数?
-
@njzk2 我认为这是一个可能的解决方案,但我以前从未从事过这个工作。我不知道如何实现
-
使用地图而不是集合,例如使用
map.set(year, map(getOrDefault(year, 0) + 1)而不是set.add(year)