Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I need something like a DataTable in Java

I have looked around but cannot seem to find anything quite like i need.

I need to read in a CSV file with column headers eg:

NAME;AGE;HEIGHT
dan;36;180
john;31;181
ben;30;190

what object can i parse it into read where i can then reference it like so:

object.name = (string) someSortOfDataStructure["NAME"];
object.name = (int) someSortOfDataStructure["AGE"];

or

object.name = someSortOfDataStructure.getColumn("NAME");

In C# I can do this with something like a DataTable / DataRow.

like image 552
Dan Harvey Avatar asked Apr 16 '26 09:04

Dan Harvey


1 Answers

Think OOP. You need to create a Person class with the properties name, age and height.

public class Person {

  private String name;
  private String age;
  private String height;

  // Getter and setter methods...
}

Next, read CSV file line by line using a BufferedReader. For each line you want to split the line using line.split(";"); to give you an String[] containing the tokens.

For the line you can now create a Person from the tokens;

Person person = new Person();
person.setName(tokens[0]);
person.setAge(tokens[1]);
person.setHeight(tokens[2]);

Note that this assumes the positions of the columns. If you want to remove this assumption you need to Map the header to a position.

String headerLine = "NAME;AGE;HEIGHT";
String[] headers = headerLine.split(";");
Map<String,Integer> map = new HashMap<String,Integer>();
for (int i=0; i<headers.length; i++) {
  map.put(headers[i], i);
}

You can then get the position of a column by it's name;

Person person = new Person();
person.setName(tokens[map.get("NAME")]);
person.setAge(tokens[map.get("AGE")]);
person.setHeight(tokens[map.get("HEIGHT")]);

Table type classes are an anti-pattern. They tend to appear when the programmer can't be bothered to think in terms of Objects. I often see Table classes in legacy java applications and its a real PITA to work with them. Don't do it.

like image 87
Qwerky Avatar answered Apr 18 '26 23:04

Qwerky