接触java这么多年,我们用Collection存储单值,用Map存储键值对。如果要通过两个键来确定一个值得,我一般就是用Map里面套一个Map。今天介绍一个Guava提供的数据结构,Table<R,C,V> 各个参数的意义是(行、列、值),即一个行号和一个列号对应一个值。就像一个表格一样。下面我们来看看这个数据结构存储数据的方式
public class Test {
public static void main(String[] a){
//创建一个表格
HashBasedTable<Integer, Integer, String> table = HashBasedTable.create();
//往里面放9个元素 横三 竖三
table.put(1, 1, "table1");
table.put(1, 2, "table2");
table.put(1, 3, "table3");
table.put(2, 1, "table4");
table.put(2, 2, "table5");
table.put(2, 3, "table6");
table.put(3, 1, "table7");
table.put(3, 2, "table8");
table.put(3, 3, "table9");
//通过X、Y坐标获取指定元素
System.out.println("通过X、Y坐标获取指定元素 :"+table.get(2, 2));
//所有的列 的 键
System.out.println("所有的列 的 键:"+table.columnKeySet());
//将每一列划分为一个map
Map<Integer,Map<Integer,String>> columnMaps = table.columnMap();
System.out.println("将每一列划分为一个map:"+columnMaps);
//获取具体的某一列的map
Map<Integer,String> column2Map = table.column(2);
System.out.println("获取具体的某一列的map:"+column2Map);
//所有的行 的 键
System.out.println("所有的行 的 键:"+table.rowKeySet());
//将每一行划分为一个map
Map<Integer,Map<Integer,String>> rowMaps = table.rowMap();
System.out.println("将每一行划分为一个map:"+rowMaps);
//获取集体的某一行的map
Map<Integer, String> row2Map = table.row(2);
System.out.println("获取集体的某一行的map:"+row2Map);
}
}
输出结果:
通过X、Y坐标获取指定元素 :table5
所有的列 的 键:[1, 2, 3]
将每一列划分为一个map:{1={1=table1, 2=table4, 3=table7}, 2={1=table2, 2=table5, 3=table8}, 3={1=table3, 2=table6, 3=table9}}
获取具体的某一列的map:{1=table2, 2=table5, 3=table8}
所有的行 的 键:[1, 2, 3]
将每一行划分为一个map:{1={1=table1, 2=table2, 3=table3}, 2={1=table4, 2=table5, 3=table6}, 3={1=table7, 2=table8, 3=table9}}
获取集体的某一行的map:{1=table4, 2=table5, 3=table6}