zoukankan      html  css  js  c++  java
  • java--树封装

    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.运行结果如下:

  • 相关阅读:
    Java实现Excel导入数据库,数据库中的数据导入到Excel
    MySQL如何把A表查询出来的某个字段的数据插入到新增的字段的下面
    MySQL怎么把小数转换为百分比?
    linux上安装python3和pip----最简单的安装
    linux pip 安装包的时候报错:Could not find a version that satisfies the requirement bs4 (from versions: ) No matching distribution found for bs4
    Excel提取中文
    关于Excel的一些小技巧
    5-24 树种统计 (25分)
    POJ 2663 Tri Tiling
    5-3 树的同构 (25分)
  • 原文地址:https://www.cnblogs.com/jvStarBlog/p/10957886.html
Copyright © 2011-2022 走看看