I am learning how to read Excel workbooks in Java and want to know what a good Data Structure will be for holding Column names with the values under them.
I want to be able to call a method: getColumnValue(String columnName, int indexOfValue)
and get the value at that position for the specified column name.
I was thinking of a Hash Table with Linked Lists. However, that seems like a lot of overhead as there can be any number of columns and values associated with them.
What would be a good recommendation for this? Thanks in advance!
Best Answer
Assumed you need a generic solution, where the program is not tied to a specific column structure at run time, you can use an
ArrayList
of rows, where each row is a string arrayString[]
. You will need an additionalHashTable<String,int>
to store the mapping of the column name to the column index (aHashMap
will probably work, either). So if you haveyou can implement
getColumnValue
byYou may consider to add some error handling here, some code which determines the column names and some more code which reads the excel rows into the
String
arrays with one entry per column. If you need the values in a typed form, consider to replace theString[]
rows byObject[]
and store the cell content as objects of typeString
,Integer
,Double
orDate
. You can also implement a speficic classCellContent
and store your rows asCellContent[]
arrays, if you have specific requirements and a need to implement specific behaviour or methods for a content element.Note this is a rough scetch of a general purpose solution. One can modify this and create different variants, for more specific requirements.
If you need a less generic variant, because your program expects a specific column structure, best solution is probably to create a specific DTO class
MyRowType
for holding the specific values of a row, and use a variable likeArrayList<MyRowType> tableValues
for storing the table content.