gpt4 book ai didi

java - 为什么 Apache commons csv 解析器将唯一数据附加到第二个结果集中?

转载 作者:太空宇宙 更新时间:2023-11-04 10:06:58 25 4
gpt4 key购买 nike

我的目录中有 2 个 CSV 文件(district1.csv、district2.csv),每个文件都包含一列 schoolCode。当我使用 Apache commons CSV 库读取这两个 CSV 文件时,我正在读取 schoolCode 列的不同值并对结果进行计数。这是我的代码:

public void getDistinctRecordCount() throws IOException {
Set<String> uniqueSchools = new HashSet<>();
int numOfSchools;
String SchoolCode;

//Filter to only read csv files.
File[] files = Directory.listFiles(new FileExtensionFilter());

for (File f : files) {
CSVParser csvParser;
CSVFormat csvFormat = CSVFormat.DEFAULT.withFirstRecordAsHeader().withIgnoreHeaderCase().withTrim();
reader = Files.newBufferedReader(Paths.get(Directory + "\\" + f.getName() ), StandardCharsets.ISO_8859_1);
csvParser = CSVParser.parse(reader, csvFormat);
for (CSVRecord column : csvParser) {
SchoolCode = column.get("School Code");
uniqueSchools.add(SchoolCode);
}
Logger.info("The list of Schools for " + f.getName() + " are: " + uniqueSchools);
numOfSchools = uniqueSchools.size();
Logger.info("The total count of Schools for " + f.getName() + " are: " + numOfSchools);
Logger.info("-----------------------");
}
}

这是我的输出:

[INFO ] [Logger] - The list of Schools for district1.csv are: [01-0003-002, 01-0003-001]
[INFO ] [Logger] - The total count of Schools for district1.csv are: 2
[INFO ] [Logger] - The list of Schools for district2.csv are: [01-0003-002, 01-0003-001, 01-0018-004, 01-0018-005, 01-0018-002, 01-0018-003, 01-0018-008, 01-0018-006]
[INFO ] [Logger] - The total count of Schools for district2.csv are: 8

问题:从 District1.csv 结果读取的两个值被附加到 District2.csv 结果中,使 District2.csv 的计数减少 2(实际正确值应为 6)。它是如何附加的?

最佳答案

如果您不需要所有学校的集合,您可以移动 uniqueSchools内部循环或 clear它:

for (File f : files) {
uniqueSchools.clear();

您还可以保存在 Map<String, String>每个文件的学校或每个文件创建一组,记录计数,然后 addAll设置为uniqueSchools

Set<String> currentSchools = new HashSet<>();
..
currentSchools.add(SchoolCode);
Logger.info("The list of Schools for " + f.getName() + " are: " + currentSchools);
numOfSchools = currentSchools.size();
Logger.info("The total count of Schools for " + f.getName() + " are: " + numOfSchools);
uniqueSchools.addAll(currentSchools);
  • 考虑变量的第一个字母小写(驼峰式),例如更改SchoolCodeschoolCodeLoggerlogger

关于java - 为什么 Apache commons csv 解析器将唯一数据附加到第二个结果集中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52799919/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com