2

I am trying to open a CSV via LoadTable with Processing 2 then parse a column as an array.

I have this so far:

Table table;
void setup() {
table = loadTable("random.csv", "header");

If I do something like this:

for (TableRow row : table.rows()) {
    int nums = row.getInt("Column1");
    println(nums);
    }

It displays all of the values in my table like it should. I would like to now store this into an array... e.g. int [ ]

Any help?

p3hndrx
  • 103
  • 9

3 Answers3

2

Just create array and store it in it :)

    int size = table.rows().size();
    int[] array = new int[size];        
    int i = 0;
    for (TableRow row : table.rows()) {
        int nums = row.getInt("Column1");
        println(nums);
        array[i] = nums;
        i++;
    }
libik
  • 22,239
  • 9
  • 44
  • 87
0

Although @Libik's answer will work, another option is to create an ArrayList

List<Integer> myNums = new ArrayList<>();
for (TableRow row : table.rows()) {
    int nums = row.getInt("Column1");
    myNums.add(nums)
    println(nums);
    }

The advantage here is the ArrayList can grow as you need it to and needn't be pre-allocated.

If you specifically need an array of ints for the final result, and not an ArrayList, the existing answers to this SO question talk about how to do the conversion.

Community
  • 1
  • 1
paisanco
  • 4,098
  • 6
  • 27
  • 33
0

It can also be done using getIntColumn() in one line: int[] num = table.getIntColumn("Column1")

So maybe it's even not necessary as you can do something like table.getIntColumn("id")[10]

here a running example:

//building a sample table
//not your case...
Table table;
TableRow[] someRows = new TableRow[40];

void setup() {

  table = new Table();

  table.addColumn("id");

  for (int i=0; i < someRows.length; i++) {
    someRows[i] = table.addRow();
    someRows[i].setInt("id", i);
  } 

  ///


  //here :) one line.
  int[] ids = table.getIntColumn("id");


  println(ids);

  // or direct approach
  println("without intermediary Array: row 10 = " + table.getIntColumn("id")[10]);
}
v.k.
  • 2,826
  • 2
  • 20
  • 29