- Table
当我们需要多个索引的数据结构时,大多数时候我们会选择 Map<String,Map<String,Object>> M a p < S t r i n g , M a p < S t r i n g , O b j e c t >> 这种Map套Map这种很繁琐的数据结构;最近在学习Guava的时候发现已经提供的有Table集合类型,来支持这种使用场景,Table支持了row和cloumn这种二维的结构,并且提供了多种的视图:
public static void main(String[] args) {
Table<Integer, Integer, Integer> table = HashBasedTable.<Integer, Integer, Integer>create();
table.put(1, 2, 3);
//允许row和column确定的二维点重复
table.put(1, 6, 3);
//判断row和column确定的二维点是否存在
if(table.contains(1, 2)) {
table.put(1, 4, 4);
table.put(2, 5, 4);
}
System.out.println(table);
//获取column为5的数据集
Map<Integer, Integer> column = table.column(5);
System.out.println(column);
//获取rowkey为1的数据集
Map<Integer, Integer> row = table.row(1);
System.out.println(row);
//获取rowKey为1,columnKey为2的的结果
Integer value = table.get(1, 2);
System.out.println(value);
//判断是否包含columnKey的值
System.out.println(table.containsColumn(3));
//判断是否包含rowKey为1的视图
System.out.println(table.containsRow(1));
//判断是否包含值为2的集合
System.out.println(table.containsValue(2));
//将table转换为Map套Map格式
Map<Integer, Map<Integer, Integer>> rowMap = table.rowMap();
System.out.println(rowMap);
//获取所有的rowKey值的集合
Set<Integer> keySet = table.rowKeySet();
System.out.println(keySet);
//删除rowKey为1,columnKey为2的元素,返回删除元素的值
Integer res = table.remove(1, 2);
//清空集合
table.clear();
System.out.println(res);
System.out.println(table);
}
运行结果集:
{1={4=4, 2=3, 6=3}, 2={5=4}}
{2=4}
{4=4, 2=3, 6=3}
3
false
true
false
{1={4=4, 2=3, 6=3}, 2={5=4}}
[1, 2]
3
{1={4=4, 6=3}, 2={5=4}}
Table有以下实现:
HashBasedTable:基于
HashMap<R,HashMap<C,V>>
H
a
s
h
M
a
p
<
R
,
H
a
s
h
M
a
p
<
C
,
V
>>
的实现。
TreeBasedTable:基于
TreeMap<R,TreeMap<C,V>>
T
r
e
e
M
a
p
<
R
,
T
r
e
e
M
a
p
<
C
,
V
>>
的实现。
ImmutableTable:基于
ImmutableMap<R,ImmutableMap<C,V>>
I
m
m
u
t
a
b
l
e
M
a
p
<
R
,
I
m
m
u
t
a
b
l
e
M
a
p
<
C
,
V
>>
的实现。
TreeBasedTable的使用方式跟HashBasedTable基本相同,在这里就不在复述了。。。