这个小例子介绍如何使用Guava提供的Table类。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
import com.google.common.collect.HashBasedTable; import com.google.common.collect.Table; public class TryTable { public static void main(String[] args) { Table<String, String, String> aTable = HashBasedTable.create(); // create a table; for (char a = 'A'; a <= 'C'; ++a) { for (char b = '1'; b <= '3'; ++b) { // put() // first is rowKey, second is columnKey, third is the value. aTable.put(Character.toString(a), Character.toString(b), String.format("%c%c", a, b)); } } // query a specific column System.out.println(aTable.column("2")); // {A=A2, B=B2, C=C2} // query a specific row System.out.println(aTable.row("B")); // {3=B3, 2=B2, 1=B1} // query a cell System.out.println(aTable.get("B", "2")); // B2 // contains test System.out.println(aTable.contains("D", "1")); // false System.out.println(aTable.containsColumn("3")); // true System.out.println(aTable.containsRow("C")); // true System.out.println(aTable.columnMap()); // {3={A=A3, B=B3, C=C3}, 2={A=A2, B=B2, C=C2}, 1={A=A1, B=B1, C=C1}} System.out.println(aTable.rowMap()); // {A={3=A3, 2=A2, 1=A1}, B={3=B3, 2=B2, 1=B1}, C={3=C3, 2=C2, 1=C1}} // Remove a cell System.out.println(aTable.remove("B", "3")); // B3 } } |