MantaMan
MantaMan

Reputation: 137

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);
}

Upvotes: 6

Views: 1899

Answers (1)

DPM
DPM

Reputation: 2030

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.

Upvotes: 5

Related Questions