I have a csv file with headers in order fname,mname,lname and a csv parser to parse this. I am reading the file line by line and splitting by delimitter (",") and according to index i'll get the values 0=fname, 1=mname, 2=lname.
Now again if a csv comes with headers in the order lname,fname and mname i have to change the code again. I want to write a generic parser which regardless of the order of the header stores the value in respective fields. Any suggestions?
Best How To :
I suggest not to write a generic parser and use Apache Commons CSV.
As you don't know the order of the columns, use CSVFormat as described in its documentation:
Referencing columns safely
If your source contains a header record, you can simplify your code and safely reference columns, by using withHeader(String...) with no arguments:
This causes the parser to read the first record and use its values as column names. Then, call one of the CSVRecord get method that takes a String column name argument:
String value = record.get("Col1");
This makes your code impervious to changes in column order in the CSV file.