Data structure for storing the contents of the analyzed CSV file

I am trying to figure out which best approach would be to parse a csv file in Java. Now each line will contain X information. For example, the first line can contain up to 5 string words (with commas separating them), while in the next few lines there may be 3 or 6 or something else.

My problem is not reading the lines from the file . Just to be clean. My problem is that the data structure is best to hold every line as well as every word in that line?

At first I thought about using a 2D array, but the problem is that the dimensions of the array should be static (the second index size will contain the number of words in each row, which may differ from row to row),

Here are the first few lines of the CSV file:

0,MONEY
1,SELLING
2,DESIGNING
3,MAKING
DIRECTOR,3DENT95VGY,EBAD,SAGHAR,MALE,05/31/2011,null,0,10000,07/24/2011
3KEET95TGY,05/31/2011,04/17/2012,120050
3LERT9RVGY,04/17/2012,03/05/2013,132500
3MEFT95VGY,03/05/2013,null,145205
DIRECTOR,XKQ84P6CDW,AGHA,ZAIN,FEMALE,06/06/2011,null,1,1000,01/25/2012
XK4P6CDW,06/06/2011,09/28/2012,105000
XKQ8P6CW,09/28/2012,null,130900
DIRECTOR,YGUSBQK377,AYOUB,GRAMPS,FEMALE,10/02/2001,12/17/2007,2,12000,01/15/2002
+3
source share
4 answers

You can use Map<Integer, List<String>>. The keys are the line numbers in the csv file, and List are the words on each line.

Extra point: you probably end up using the method List#get(int)quite often. Do not use a linked list if this is the case. This is due to the fact that get(int)for the linked list - O (n). I think that ArrayListis your best option here.

Edit (based on AlexWien observation):

, , , ArrayList<ArrayList<String>>. .

+2

. .

+3

The best way is to use the CSV parser, for example http://opencsv.sourceforge.net/ . This analyzer uses List of String [] to store data.

+2
source

Use List<String>()that can dynamically expand in size.

If you want to have 2 dimensions, use List<List<String>>().

Here is an example:

List<List<String>> data = new ArrayList<List<String>>();
List<String> temp = Arrays.asList(someString.split(","));
data.add(temp);

put this in some kind of loop and get your data.

0
source

All Articles