I’m writing some java code that’s supposed to parse csv files with different column types and values. A basic file looks something like this (CSV), without the header/column row. To make things simpler when processing the file, I want to be able to access each cell’s index value using the column name. I don’t want to use a CSV parser at the moment.
Column1 | Column2 | Column3 |...
--------+---------+---------+---
val10 | val20 | val30 |
val11 | val21 | val31 |
val12 | val22 | val32 |
... | ... | ... |
I thought about using ArrayList of column names (in order), since enum doesn’t convert back to integers as in C++. This way I could do something like:
ArrayList<String> columnNames = new ArrayList<String>();
columnNames.add("Column1");
columnNames.add("Column2");
columnNames.add("Column3");
// read each line from the file ...
String[] row = line.trim().split(",");
String col2 = row[ columnNames.indexOf("Column2") ];
I’m fairly new to Java – is there a better / smarter way to do this? thanks.
Your code works. however two points you may want to re-think, if you are looking for “better” way:
indexOf(object) method of List is not so fast. costs O(n). if you maintain a
Map<columnNameString, indexNumber>, and get the index from colName, it should be faster than your current impl. Apart from that, in java, you can get different types of value from an enum. you even could let your enum implement interfaces.you should do some exception handling. what if one line in your file missing a (or more) column(s). Your current codes will throw OutOfbound exception. however I hope this was already done in your real codes.