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

我在一个目录中有 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)。它是如何附加的?


12345678_0001
浏览 152回答 1
1回答

温温酱

如果您不需要设置所有学校,您可以uniqueSchools在循环内移动或清除它:for (File f : files) {&nbsp; &nbsp;uniqueSchools.clear();您还可以将Map<String, String>每个文件保存在学校中或为每个文件创建一个集合,记录计数,然后将所有集合添加到uniqueSchoolsSet<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);&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;uniqueSchools.addAll(currentSchools);考虑小写(驼峰式)变量的第一个字母,例如更改SchoolCode为schoolCode和Logger到logger
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java