1.为什么要用HashBasedTable 这种数据结构?
在实际工作中,如果我们想用索引数据结构的时候,我相信大多数人会使用 Map嵌套Map的数据结构,如 Map<String,Map<String,Object>>,这种Map套Map数据结构,操作起来很繁琐的。
2.HashBasedTable 是什么样的结构?
由rowkey + columnKey 为索引,存储 value的。
3.引入依赖jar
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>19.0</version>
</dependency>
4.HashBasedTable 使用方法
import java.util.Map;
import java.util.Set;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Table;
public class GuavaTester {
public static void main(String args[]){
//create a table
Table<String, String, String> employeeTable = HashBasedTable.create();
//initialize the table with employee details
employeeTable.put("IBM", "101","Mahesh");
employeeTable.put("IBM", "102","Ramesh");
employeeTable.put("IBM", "103","Suresh");
employeeTable.put("Microsoft", "111","Sohan");
employeeTable.put("Microsoft", "112","Mohan");
employeeTable.put("Microsoft", "113","Rohan");
employeeTable.put("TCS", "121","Ram");
employeeTable.put("TCS", "122","Shyam");
employeeTable.put("TCS", "123","Sunil");
//get Map corresponding to IBM
Map<String,String> ibmEmployees = employeeTable.row("IBM");
System.out.println("List of IBM Employees");
for(Map.Entry<String, String> entry : ibmEmployees.entrySet()){
System.out.println("Emp Id: " + entry.getKey() + ", Name: " + entry.getValue());
}
//get all the unique keys of the table
Set<String> employers = employeeTable.rowKeySet();
System.out.print("Employers: ");
for(String employer: employers){
System.out.print(employer + " ");
}
System.out.println();
//get a Map corresponding to 102
Map<String,String> EmployerMap = employeeTable.column("102");
for(Map.Entry<String, String> entry : EmployerMap.entrySet()){
System.out.println("Employer: " + entry.getKey() + ", Name: " + entry.getValue());
}
}
}
//更多请阅读:https://www.yiibai.com/guava/guava_table.html
运行结果:
List of IBM Employees
Emp Id: 102, Name: Ramesh
Emp Id: 101, Name: Mahesh
Emp Id: 103, Name: Suresh
Employers: IBM TCS Microsoft
Employer: IBM, Name: Ramesh
5.总结:
HashBasedTable:基于HashMap<R,HashMap<C,V>>的实现。
TreeBasedTable:基于TreeMap<R,TreeMap<C,V>>的实现。
ImmutableTable:基于ImmutableMap<R,ImmutableMap<C,V>>的实现。
--------------------------------------------------------------------------------------------------------------------------------
一件事,就算再美好,一旦没有结果,就不要再纠缠!