Java中HashMap是一个key对应一个value,正好在项目中遇到需要两个key的去mapping一个value的情况,发现Guava的Table非常完美的满足了这样一个矩阵的数据结构,我得mark下,so show my code:
@Test
public void guavaTableTest() {
Table<Integer, Integer, String> animalTable = HashBasedTable.create();
// rowKey和columnKey决定一个value
animalTable.put(1, 2, "cat"); // rowKey: 1 columnKey: 2 value: cat
animalTable.put(1, 2, "wolf"); // 两个key一样的话, 覆盖 上一个的值
System.out.println(animalTable); // {1={2=wolf}}
System.out.println(animalTable.get(1, 3)); // null
System.out.println(animalTable.get(1, 2)); // wolf
Table<Integer, Integer, String> zooTable = HashBasedTable.create();
zooTable.put(1, 2, "dog");
zooTable.put(1, 3, "lion");
animalTable.putAll(zooTable); // zooTable会覆盖掉animalTable中相同的rowKey和columnKey指向的值
System.out.println(animalTable); // {1={2=dog, 3=lion}}
}
Output:
{1={2=wolf}}
null
wolf
{1={2=dog, 3=lion}}
参考:
细节可参考Guide to Guava Table
经常看他们家的文章,写得通俗易懂!