Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

NamedCsvReader should have support for returning default value if field is not present #97

Closed
anuragagarwal561994 opened this issue Nov 14, 2023 · 3 comments

Comments

@anuragagarwal561994
Copy link

Is your feature request related to a problem? Please describe.
We have a use-case where we have 2 different csv files one where 3 columns are present and another where 5 columns are present. We want to be able to keep the fields as required and 2 optional. In case we do row.getField('NOT_PRESENT_COLUMN') as of now we get an error, we can instead have a method like row.getFieldOrDefault(field_name, default_value) which if the field is not present will return the default value.

However this should not be confused with the data being present as null.

Describe the solution you'd like
Described above

@osiegmar
Copy link
Owner

Thank you for bringing this up!

Just added this functionality by 5ebb7d5. This allows something like this:

try (var csv = NamedCsvReader.builder().build("col1,col2\nfoo").stream()) {
    csv.forEach(rec -> {
        var col1 = rec.findField("col1").orElse("default");
        var col2 = rec.findField("col2").orElse("default");
        System.out.printf("col1: %s, col2: %s%n", col1, col2);
    });
}

Will be part of version 3 which will be released within the next few months.

@anuragagarwal561994
Copy link
Author

Thanks for update, actually later I realised that I can instead use csvRow.getFields() which gives a map and then I can check containsKey

I was about to close the issue.

@osiegmar
Copy link
Owner

Go ahead and use it, if it fits your need. As that methods requires another "bigger" object (Map) being built for every record, I'm happy to also offer a more elegant and less resource consuming way to access optional fields.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants