【问题标题】:Using apache commons csv: I'm trying to remove a set of records from a List<CSVRecord> but it's not removing all of them/使用 apache commons csv:我正在尝试从 List<CSVRecord> 中删除一组记录,但它并没有删除所有记录/
【发布时间】:2017-10-14 21:10:06
【问题描述】:

我有一个从文件中解析的 CSVRecords 列表:

https://drive.google.com/file/d/0ByASC8p2MeUKZlhTdkxETXV2U3M/view?usp=sharing

使用以下代码:

public static List<CSVRecord> getRecords(File file) throws Exception {
        Reader in = new FileReader(file);
        CSVParser parser = new CSVParser(in, CSVFormat.RFC4180);
        List<CSVRecord> records = parser.getRecords();
        parser.close();
        records.remove(0);
        return records;
    }

其中一列是 p(pft),我正在尝试删除 p(pft) 小于 75 的所有记录: (optStratCsv 是 csvRecords 的列表)

           for (int i = 0; i < optStratCsv.size(); i++) {
                if (Integer.parseInt(optStratCsv.get(i).get(14)) < 75) {
                    optStratCsv.remove(i);
                }
            }

但是,虽然它应该给我一个大约 6000 条记录的列表,但它给了我一个大约 9000 条记录的列表,所以很明显我做错了什么。我想弄清楚我做错了什么。 干杯。

【问题讨论】:

    标签: java apache csv file-io


    【解决方案1】:

    这是一个想法。不要删除记录。而是复制您想要的记录并将其返回。因此,如果记录不是 p(pft) 小于 75,则复制到临时 CSVRecord 列表。然后返回温度。

    每次从optStratCsv 中删除记录时,for (int i = 0; i &lt; optStratCsv.size(); i++) 中的大小都会发生变化。有意义吗?

    【讨论】:

    • 哦,我明白了。非常感谢!
    • @MishaTsirlin,如果此答案对您有所帮助,请接受答案。谢谢,
    • 对不起,我现在这样做了
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-16
    • 2011-08-18
    • 2011-03-30
    • 1970-01-01
    • 1970-01-01
    • 2012-10-01
    相关资源
    最近更新 更多