【问题标题】:Java filter values when read csv with Jackson使用 Jackson 读取 csv 时的 Java 过滤器值
【发布时间】:2024-05-16 14:50:01
【问题描述】:

我来找你是因为我在读取 csv 和使用 Jackson 创建地图时遇到问题。为了读取文件并将其关联到地图,我使用以下代码:

private static <T, R extends IndexedData<T>> List<R> readFile(File csvFile, Class<R> cls) throws Exception {
    CsvMapper csvMapper = new CsvMapper();
    CsvSchema csvSchema = csvMapper.typedSchemaFor(cls).withHeader().withStrictHeaders(true);
    List list = csvMapper.readerFor(cls)
            .with(csvSchema.withColumnSeparator(';'))
            .with(CsvParser.Feature.SKIP_EMPTY_LINES)
            .readValues(csvFile)
            .readAll();
    return list;
}

但是如何根据属性的值过滤数据?

例如,我在一列中有一个 ID,只有当该值等于“038”时,我才想在地图中读取并存储该行

使用的代码读取整个文件并创建一个包含所有值的 HashMap,但我想只将某些具有定义条件的值添加到映射中。 知道文件有相当大的体积,我无法读取所有的值,稍后过滤Map。

欢迎任何帮助:)

亲切

【问题讨论】:

  • 您不必阅读所有文件以确保最后一行不符合您想要的条件吗?
  • 当阅读是,但我只想在我的 HashMap 中添加符合条件的值,否则我有一个饱和的内存问题
  • 我在你的代码中没有看到 HashMap。

标签: java csv filter jackson


【解决方案1】:

我不确定是否可以直接使用CsvMapper。 一个选项是在尝试反序列化它们之前过滤这些行。像这样:

我这里用一个简单的类和csv文件给你举个例子

class MyClass {
    private String id;
    private String name;
    // Getters/Setters
}

以及以下 CSV 文件

id;name
1;pip
2;pap
3;pop
4;zip
5;zap
6;zop

您可以这样做:此示例仅反序列化名称中带有“o”的行

public static void main(String[] args) throws Exception {
    readFile(new File("file.csv"));
}



private static List<MyClass> readFile(File csvFile) throws Exception {
    List<String> lines = filterFile(csvFile);

    CsvMapper csvMapper = new CsvMapper();
    CsvSchema csvSchema = csvMapper.typedSchemaFor(MyClass.class).withHeader().withStrictHeaders(true);

    List list = csvMapper.readerFor(MyClass.class)
            .with(csvSchema.withColumnSeparator(';'))
            .with(CsvParser.Feature.SKIP_EMPTY_LINES)
            .readValues(String.join("\n", lines))
            .readAll();

    return list;
}


// This method goes through the file and filter out all lines where the name does not contain an "o"
// It also keeps the header because it is needed for the CsvMapper
private static List<String> filterFile(File csvFile) {
    List<String> list = new ArrayList<>();
    boolean header = true;
    try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
        String line;
        String[] tokens;
        while ((line = br.readLine()) != null) {
            tokens = line.split(";");
            if(header || tokens[1].contains("o")) {
                header = false;
                list.add(line);
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return list;
}

返回 2 个名为“pop”和“zop”的 MyClass 对象

【讨论】: