I have a csv file with unknown amount of columns and row. The only thing I know is that each entry is separated by a comma. Can I use the split method to convert each line of the data into an array and then can I store that Array into an Arraylist. One of the things that concerns me is would I be able to rearrange the Arraylist alphabetically or numerically.
Share
There are several questions here so I’ll cover each point individually.
This would work as you expect in the naive case. However, it doesn’t know anything about escaping; so if a comma is embedded within a field (and properly escaped, usually by double-quoting the whole field) the simple split won’t do the job here and will chop the field in two.
If you know you’ll never have to deal with embedded commas, then calling
line.split(",")is acceptable. The real solution however is to write a slightly more involved parse method which keeps track of quotes, and possibly backslash escapes etc.You certainly could have an
ArrayList<String[]>, but that doesn’t strike me as particularly useful. A better approach would be to write a simple class for whatever it is the CSV lines are representing, and then create instances of that class when you’re parsing each line. Something like this perhaps:Then you’d have a list of Orders, which more accurately represents what you have in the file (and in memory) than a list of string-arrays.
Sure – the standard collections support a
sortmethod, into which you can pass an instance ofComparator. This takes two instances of the object in the list, and decides which one comes before the other.So following on from the above example, if you have a
List<Order>you can pass in whatever comparator you want to sort it, for example: