Search code examples
javaiterationguava

Guava Table: how to iterate over columns when height and width is not known and table is sparse


My Java 8 code is being giving an instance of a Guava Table<Integer,Integer,Fizzbuzz> where the row and column keys are non-negative integers (0+) and the values in each cell is an instance of some Fizzbuzz POJO.

Most of the time the Table will be the hashed implementation that comes from calling HashBasedTable.create(), however this is not necessarily _always) going to be the case. So I (really) need a solution that works for any Table subclass.

So I am trying to range over all the rows, and all the columns of the table, without knowing ahead of time how many rows or columns there are. My best attempt thus far:

for (Integer rowKey : myTable.rowKeySet()) {
    int colKey = 0;

    Fizzbuzz val;
    while ((val = myTable.get(rowKey, colKey)) != null) {

        // increment colKey
        colKey++;

        // do some processing with the 'val' Fizzbuzz...
    }

}

Although inefficient and somewhat wonky, this would work, except for the fact that is valid for my table to be sparse, meaning, not every single cell value/address (row + col combo) needs to be populated. Its fine for nulls to exist.

I've poured over the Guava Table docs and countless online examples and for the life of me I can't figure out how to properly (and efficiently!) range over rows and columns when the table is sparse (allows nulls). Any ideas?


Solution

  • You can use rowMap() to get a Map<R, Map<C,V>>.

    You can iterate this:

    table.rowMap().forEach((rowKey, row) -> {
      row.forEach((colKey, value) -> {
        // Do something for each row key/col key/value.
      });
    });
    

    (Ofc you can use enhanced for loops here. It's just more concise to write with forEach on my phone).