双键单值Map--->Table类 键值可以相同 。
常用的方法:
* 1)cellSet() 可以获取map中所有数据。 这里要注意一下它的返回类型
* 2)Tables.transpose() map中的第一列key值一第二列key值交换
* 3)rowKeySet() 获取map中第一列key值
* 4)columnKeySet() 获取第二列key值
* 5)row()根据第一列key值寻找第二列key值和第三列value值 ,返回Map类型
* 6)column()根据第二列key值寻找第一列key值和第三列value值 ,返回Map类型
public static void main(String[] args) {
Table<String, String, Integer> table = HashBasedTable.create();
// 装入测试数据
table.put("陈虹君", "java", 90);
table.put("陈虹君", "数据结构", 95);
table.put("高淇", "java", 80);
table.put("王伟", "数据结构", 70);
table.put("王伟", "java", 60);
System.out.println("=============所有的数据==============");
Set<Cell<String, String, Integer>> cells = table.cellSet();
for (Cell<String, String, Integer> temp : cells) {
System.out.println(temp.getRowKey() + "-->" + temp.getColumnKey()
+ "-->" + temp.getValue());
}
System.out.println("\n============学生与课程位置对调成绩================");
Table<String, String, Integer> table2 = Tables.transpose(table);
Set<Cell<String, String, Integer>> cells2 = table2.cellSet();
for (Cell<String, String, Integer> temp : cells2) {
System.out.println(temp.getRowKey() + "-->" + temp.getColumnKey()
+ "-->" + temp.getValue());
}
System.out.println("============所有的学生================");
Set<String> stus = table.rowKeySet();
for (String temp : stus) {
System.out.print(temp + "\t");
}
System.out.println("\n============所有的课程================");
Set<String> courses = table.columnKeySet();
for (String temp : courses) {
System.out.print(temp + "\t");
}
System.out.println("\n============所有的成绩================");
Collection<Integer> grades = table.values();
for (Integer temp : grades) {
System.out.print(temp + "\t");
}
System.out.println("\n============根据学生查课程成绩================");
System.out.print("学生\t");
for (String temp : courses) {
System.out.print(temp + "\t");
}
System.out.println();
for (String temp : stus) {
System.out.print(temp + "\t");
Map<String, Integer> map = table.row(temp);
for (String str : courses) {
System.out.print(map.get(str) + "\t");
}
System.out.println();
}
System.out.println("\n============根据课程查学生成绩================");
System.out.print("课程\t");
for (String temp : stus) {
System.out.print(temp + "\t");
}
System.out.println();
for (String temp : courses) {
System.out.print(temp + "\t");
Map<String, Integer> map = table.column(temp);
for (String str : stus) {
System.out.print(map.get(str) + "\t");
}
System.out.println();
}
}
/*
Output:
=============所有的数据==============
高淇-->java-->80
王伟-->java-->60
王伟-->数据结构-->70
陈虹君-->java-->90
陈虹君-->数据结构-->95
============学生与课程位置对调成绩================
java-->高淇-->80
java-->王伟-->60
数据结构-->王伟-->70
java-->陈虹君-->90
数据结构-->陈虹君-->95
============所有的学生================
高淇 王伟 陈虹君
============所有的课程================
java 数据结构
============所有的成绩================
80 60 70 90 95
============根据学生查课程成绩================
学生 java 数据结构
高淇 80 null
王伟 60 70
陈虹君 90 95
============根据课程查学生成绩================
课程 高淇 王伟 陈虹君
java 80 60 90
数据结构 null 70 95
*/