Table Interface
Table represents a special map where two keys can be specified in combined fashion to refer to a single value. It is similar to creating a map of maps.
package org.fool.guava.collections;
import java.util.Map;
import java.util.Set;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Table;
public class TableTest {
public static void main(String[] args) {
// Table<R,C,V> == Map<R,Map<C,V>>
// create a table
Table<String, String, String> employeeTable = HashBasedTable.create();
// initialize the table with employee details
employeeTable.put("IBM", "101", "Mahesh");
employeeTable.put("IBM", "102", "Ramesh");
employeeTable.put("IBM", "103", "Suresh");
employeeTable.put("Microsoft", "111", "Sohan");
employeeTable.put("Microsoft", "112", "Mohan");
employeeTable.put("Microsoft", "113", "Rohan");
employeeTable.put("TCS", "121", "Ram");
employeeTable.put("TCS", "122", "Shyam");
employeeTable.put("TCS", "123", "Sunil");
// get Map corresponding to IBM
Map<String, String> ibmEmployees = employeeTable.row("IBM");
System.out.println("List of IBM Employees");
ibmEmployees.forEach((id, name) -> System.out.println("Emp Id: " + id + ", Name: " + name));
// get all the unique keys of the table
Set<String> employers = employeeTable.rowKeySet();
System.out.print("Employers: ");
employers.forEach(employer -> System.out.print(employer + " "));
System.out.println();
//get a Map corresponding to 102
Map<String,String> employerMap = employeeTable.column("102");
employerMap.forEach((id, name) -> System.out.println("Emp Id: " + id + ", Name: " + name));
}
}
output
List of IBM Employees Emp Id: 103, Name: Suresh Emp Id: 101, Name: Mahesh Emp Id: 102, Name: Ramesh Employers: IBM TCS Microsoft Emp Id: IBM, Name: Ramesh