如下构建 <year,<month, LocalDate>> 的数据结构:
Map<String, Map<String, LocalDate>> dateMap = new HashMap<>(); for (int i = 2015; i <= 2016; i++) { for (int j = 1; j < 3; j++) { Map<String, LocalDate> map = dateMap.get(String.valueOf(i)); if (map == null) { map = new HashMap<>(); dateMap.put(String.valueOf(i), map); } map.put(String.valueOf(j), LocalDate.of(2016, Month.of(j), 01)); } } System.out.println(dateMap);可以看出,这里需要有null判断,比较繁琐。
//rowKey, columnKey, valueObject Table<String, String, LocalDate> dateTable = HashBasedTable.create(); for (int i = 2015; i <= 2016; i++) { for (int j = 1; j < 3; j++) { dateTable.put(String.valueOf(i), String.valueOf(j), LocalDate.of(i, Month.of(j), 01)); } } Map<String, Map<String, LocalDate>> dateMap = dateTable.rowMap(); System.out.println(dateMap); System.out.println("year=2015 ---> " + dateTable.row("2015")); System.out.println("month=1 ---> " + dateTable.column("1")); System.out.println("year=2015 and month=1 ---> " + dateTable.get("2015", "1")); System.out.println("containsColumn(3) ---> " + dateTable.containsColumn(3)); System.out.println("containsRow(2014) ---> " + dateTable.containsRow("2014")); System.out.println("columnMap ---> " + dateTable.columnMap()); System.out.println("rowMap ---> " + dateTable.rowMap()); System.out.println(dateTable.remove("2015", 1));
运行结果:
{2016={1=2016-01-01, 2=2016-02-01}, 2015={1=2015-01-01, 2=2015-02-01}} year=2015 ---> {1=2015-01-01, 2=2015-02-01} month=1 ---> {2016=2016-01-01, 2015=2015-01-01} year=2015 and month=1 ---> 2015-01-01 containsColumn(3) ---> false containsRow(2014) ---> false columnMap ---> {1={2016=2016-01-01, 2015=2015-01-01}, 2={2016=2016-02-01, 2015=2015-02-01} } rowMap ---> {2016={1=2016-01-01, 2=2016-02-01}, 2015={1=2015-01-01, 2=2015-02-01}} null可以看出使用guava的Table要比上一个例子简洁很多。