概述:
Table 代表一个特殊的映射,其中两个键可以在组合的方式被指定为单个值。它类似于创建映射的映射。
通常来说,当你想使用多个键做索引的时候,你可能会用类似 Map<FirstName, Map<LastName, Person>> 的实现,这种方式很丑陋,使用上也不友好。
Guava为此提供了新集合类型 Table,它有两个支持所有类型的键:”行”和”列”,类似效果:Map --> Table --> rowKey+columnKye+value
常见实现类:
HashBasedTable:本质上用 HashMap<R, HashMap<C, V>> 实现;
TreeBasedTable:本质上用 TreeMap<R, TreeMap<C,V>> 实现;
ImmutableTable:本质上用 ImmutableMap<R, ImmutableMap<C, V>> 实现;注:ImmutableTable对稀疏或密集的数据集都有优化。
ArrayTable:要求在构造时就指定行和列的大小,本质上由一个二维数组实现,以提升访问速度和密集Table的内存利用率。ArrayTable与其他Table的工作原理有点不同,请参见Javadoc了解详情。
示例:
public class TableTest {
@Test
public void cellsTest(){
//行,列,值
HashBasedTable<Object, Object, Object> table = HashBasedTable.create();
table.put("senvenDay",101,"xiaoming");
table.put("senvenDay",102,"xiaohong");
table.put("senvenDay",103,"xiaomei");
Set<Table.Cell<Object, Object, Object>> cells = table.cellSet();
cells.forEach(e->{
System.out.println(e.getRowKey()+"-"+e.getColumnKey()+": "+e.getValue());
});
}
@Test
public void rowAndColumnTest(){
HashBasedTable<String,String,String> table = HashBasedTable.create();
table.put("IBM", "101", "xiaoming");
table.put("IBM", "102", "xiaohong");
table.put("IBM", "103", "xiaomei");
table.put("MicroSoft", "201", "daming");
table.put("MicroSoft", "202", "dahong");
table.put("MicroSoft", "203", "damei");
table.put("Suning", "301", "zhangsan");
table.put("Suning", "302", "lisi");
table.put("Suning", "303", "wangwu");
Set<String> rowSet = table.rowKeySet();
rowSet.forEach(row->{
System.out.println("rowKey: "+row);
Map<String, String> columnMap = table.row(row);
columnMap.forEach((columnKey,value)->{
System.out.println("columnKey: "+columnKey+", value: "+value);
});
});
Map<String, String> rowMap = table.column("102");
rowMap.forEach((row,value)->{
System.out.println("row: "+row+", value: "+value);
});
}
@Test
public void tableCRUD(){
HashBasedTable<Integer,String,String> table = HashBasedTable.create();
table.put(1, "A", "zhangsan");
table.put(1, "B", "female");
table.put(1, "C", "beijing");
table.put(2, "A","lisi" );
table.put(2, "B", "male");
Assert.assertFalse(table.contains(2, "C"));
Assert.assertTrue(table.containsRow(1));
Assert.assertTrue(table.containsColumn("B"));
Assert.assertTrue(table.containsValue("beijing"));
System.out.println(table.get(1, "C")); //beijing
table.remove(1, "C");
System.out.println(table.get(1, "C")); //null
Map<String, String> columnMap = table.row(1);
System.out.println(columnMap); //{A=zhangsan, B=female}
Map<Integer, String> rowMap = table.column("B");
System.out.println(rowMap); //{1=female, 2=male}
Set<Table.Cell<Integer, String, String>> cells = table.cellSet();
cells.forEach(e->{
System.out.println(e.getRowKey()+"-"+e.getColumnKey()+": "+e.getValue());
});
// 1-A: zhangsan
// 1-B: female
// 2-A: lisi
// 2-B: male
}
}