Multimap:允许key值相同,不会覆盖掉之前的数据。用于封装类似于Map<Object,List<Object>>这种有嵌套结构的数据。Maven坐标如下:
<dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>10.0.1</version> </dependency>
1.定义树结构
public class MyTree { private String id; private String parentId; private String name; private List<MyTree> child = Lists.newArrayList(); //getter()、setter()方法。。。
public void addChild(MyTree tree){ child.add(tree); }
2.支持多层次的树封装:
//2万条数据封装耗时15ms public Collection<MyTree> getCompleteTrees() { //获取数据 List<MyTree> treeList = initList(); //树节点封装 Multimap<String, MyTree> multimap = treeNodePackageByParentId(treeList); //获取根节点 Collection<MyTree> rootNodeList = multimap.get("0"); //添加子节点 addTreeNodeDependency(rootNodeList, multimap); return rootNodeList; }
//按parentId聚合 private Multimap<String, MyTree> treeNodePackageByParentId(List<MyTree> treeList) { Multimap<String, MyTree> multimap = HashMultimap.create(); for (MyTree treeNode : treeList) { multimap.put(treeNode.getParentId(), treeNode); } return multimap; }
//添加依赖关系 private void addTreeNodeDependency(Collection<MyTree> rootTreeList, Multimap<String, MyTree> multiMap) { for (MyTree parentTreeNode : rootTreeList) { addChildNode(parentTreeNode, multiMap); } } private void addChildNode(MyTree parentTreeNode, Multimap<String, MyTree> multiMap) { String id = parentTreeNode.getId(); for (MyTree chileTreeNode : multiMap.get(id)) { String childId = chileTreeNode.getId(); parentTreeNode.addChild(chileTreeNode); if (multiMap.containsKey(childId)) { addChildNode(chileTreeNode, multiMap); } } }
//----------算法性能差,时间复杂度O(n*n),2万条数据封装耗时20s-------------
//获取数据
List<MyTree> treeList=initList(); MyTree resultTree=null;
//添加父节点和子节点依赖关系 for(MyTree outTree:treeList){ String id=outTree.getId();
//找到根节点 if("0".equals(outTree.getParentId())){ resultTree=outTree; } for(MyTree innerTree:treeList){ String parentId=innerTree.getParentId(); if(id.equals(parentId)){ outTree.addChild(innerTree); } }
}
3.数据结构如下:
id | parentId | name |
1 | 0 | 中国 |
2 | 1 | 江苏省 |
3 | 2 | 南京市 |
4 | 2 | 徐州市 |
5 | 4 | 新沂市 |
6 | 1 | 浙江省 |
7 | 6 | 杭州市 |
4.运行结果如下: