1

我在一个目录中有 2 个 CSV 文件(district1.csv、district2.csv),每个文件都包含一个 column 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)。它是如何附加的?

4

1 回答 1

0

如果您不需要设置所有学校,您可以uniqueSchools在循环内移动或清除它:

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
于 2018-10-14T06:12:29.140 回答