Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to use a for-each construction for a Guava Table?

One of the cleanest coding benefits of the modern Collections is the ability to use the for-each construction. I have below a simple general table printing method, followed by a test loading method. While this works, some kind of for-each would be a lot cleaner. Any ideas?

public void printTable(Table table)
{
    int numRows = table.rowKeySet().size();
    int numCols = table.columnKeySet().size();

    for (int i=0; i<numRows; i++) 
    {
           for (int j=0; j<numCols; j++) 
           {
               System.out.print( table.get(i,j) + " " );
           }
           System.out.println();
    }
}          
Table<Integer, Integer, Integer> table = HashBasedTable.create();
void makeTable()
{
    for (int i=0; i<4; i++) 
           for (int j=0; j<6; j++)
               table.put(i, j, i*j+2);
}
like image 674
MantaMan Avatar asked Mar 16 '12 17:03

MantaMan


People also ask

Is Guava table thread safe?

The returned table is not thread-safe or serializable, even if the underlying table is. The function is applied lazily, invoked when needed.

What is guava table?

Guava's Table is a collection that represents a table like structure containing rows, columns and the associated cell values. The row and the column act as an ordered pair of keys. The row and column act as an ordered pair of keys.


1 Answers

Why don't you just call Map<R,Map<C,V>> rowMap() and iterate over it?

Also, I think you might prefer a TreeBasedTable which accounts for row and column order, since you are using integers for the rows and columns and it seems you want to iterate on the natural order of those.

like image 55
DPM Avatar answered Oct 19 '22 13:10

DPM