Guava Table (双键Map)

1. Table 接口

  • Table 有两个key, 行键rowKey 和列键columnKey
  • 格式:KKV 行键/列键/值,等价于 Table == Map>
/**
 *  – the type of the table row keys
 *  – the type of the table column keys
 *  – the type of the mapped values
 */
public interface Table {

  V put(@ParametricNullness R rowKey, @ParametricNullness C columnKey, @ParametricNullness V value);

  V get(
      @CompatibleWith("R") @CheckForNull Object rowKey,
      @CompatibleWith("C") @CheckForNull Object columnKey);

  Set> cellSet();
  Set rowKeySet();
  Set columnKeySet();
  Collection values();

  Map row(@ParametricNullness R rowKey);
  Map column(@ParametricNullness C columnKey);
}

1.1 Table 接口实现类

2. 实战

2.1 put() / get()

@Test
public void multiKey() {
    Table table = HashBasedTable.create();

    table.put("rowKey1", "columnKey1", "value1-1");
    table.put("rowKey1", "columnKey2", "value1-2");

    table.put("rowKey2", "columnKey1", "value2-1");
    table.put("rowKey2", "columnKey2", "value2-2");

    // {rowKey1={columnKey1=value1-1, columnKey2=value1-2}, rowKey2={columnKey1=value2-1, columnKey2=value2-2}}
    System.out.println(table);
    System.out.println(table.get("rowKey1", "columnKey1"));
}

2.2 行列集合

@Test
public void multiKey2() {
    Table table = HashBasedTable.create();
    // 赋值同上

    System.out.println("元素集合: " + table.cellSet());
    System.out.println("rowKey集合: " + table.rowKeySet());
    System.out.println("columnKey集合: " + table.columnKeySet());
    System.out.println("value集合: " + table.values());
}

打印结果

元素集合: [(rowKey1,columnKey1)=value1-1, (rowKey1,columnKey2)=value1-2, (rowKey2,columnKey1)=value2-1, (rowKey2,columnKey2)=value2-2]
rowKey集合: [rowKey1, rowKey2]
columnKey集合: [columnKey1, columnKey2]
value集合: [value1-1, value1-2, value2-1, value2-2]

2.3 指定行列键查询

@Test
public void multiKey3() {
    Table table = HashBasedTable.create();
    // 赋值同上

    System.out.println(table);
    boolean hasRowKey = table.containsRow("rowKey1");
    boolean hasColumnKey = table.containsColumn("columnKey1");

    System.out.println(table.row("rowKey1"));
    System.out.println(table.row("rowKey1").keySet());

    System.out.println(table.column("columnKey1"));
    System.out.println(table.column("columnKey1").keySet());
}

打印结果:

{rowKey1={columnKey1=value1-1, columnKey2=value1-2}, rowKey2={columnKey1=value2-1, columnKey2=value2-2}}
{columnKey1=value1-1, columnKey2=value1-2}
[columnKey1, columnKey2]
{rowKey1=value1-1, rowKey2=value2-1}
[rowKey1, rowKey2]

【信息由网络或者个人提供,如有涉及版权请联系COOY资源网邮箱处理】

© 版权声明
THE END
喜欢就支持一下吧
点赞8 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容