Java converts the DataTable data type to a tree structure (Multi-tree)

Source: Internet
Author: User
Tags relational database table

Java converts the DataTable data type to a tree structure (Multi-tree)

Problem analysis: a relational database table ,:


The following four fields are displayed: Country, Province, City, and Street, which have a logical subordinate structure. Now we need to construct this data into a tree structure ,: <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + pgltzybzcm9 "http://www.2cto.com/uploadfile/Collfiles/20150602/20150602084314297.png" alt = "\">

It is not converted from the original data. It means that, as you can imagine, the same data in the dataTable is merged into cells, and then all the paths from the root to the leaf node are found, complete the task. There seems to be many plug-ins in JS that can be implemented, but I haven't found them yet in Java, so I can't write them myself. In terms of structure, it should be a multi-cross and multi-level tree structure. Therefore, it is necessary to have certain flexibility during conversion, and the hierarchy of nodes should also be clear.

First define a node class to describe the node:

public class Node {private String id;private String pId;private String text;private Map
 
   nodeValue;private String path;public Node() {}public Node(String id,String pId,String text,String path){this.id = id;this.pId = pId;this.text = text;this.path = path;}public String getId() {return id;}public void setId(String id) {this.id = id;}public String getpId() {return pId;}public void setpId(String pId) {this.pId = pId;}public String getText() {return text;}public void setText(String text) {this.text = text;}public Map
  
    getNodeValue() {return nodeValue;}public void setNodeValue(Map
   
     nodeValue) {this.nodeValue = nodeValue;}public String getPath() {return path;}public void setPath(String path) {this.path = path;}@Overridepublic String toString() {String str = "";if(this.nodeValue!=null){Set
    
     > entrySet = this.nodeValue.entrySet();for (Entry
     
       entry : entrySet) {str+=entry.getKey()+"="+entry.getValue();}}return str;}}
     
    
   
  
 

Briefly describe the original design intention:

1. the id and pid will not be mentioned, and the discerning person will see it at a glance. Text indicates the content currently displayed on the node.

2. nodeValue is a Map structure that contains text from the current node to the root node. For example, what is the description of nodeValue of Level 3 Node City = QingDao? Answer: {city = QingDao, province = ShanDong, country = China}

3. The path attribute indicates the node address or path to identify whether a node already exists. Style example:/China/ShanDong/QingDao

See the specific implementation class:

Public class MultiTree {private List
 
  
NodeList; private Node rootNode; public List
  
   
GetNodeList () {return nodeList;} public void setNodeList (List
   
    
NodeList) {this. nodeList = nodeList;} public MultiTree () {init ();} public MultiTree (List
    
     
NodeList, Node rootNode) {this (); if (nodeList! = Null) {this. nodeList = nodeList;} if (rootNode! = Null) {this. rootNode = rootNode;} private void init () {nodeList = new ArrayList
     
      
(); RootNode = new Node ("0", "-1", "0", "/");}/*** converts DataTable data to DataTree, ensure that the path is unique * @ param listMaps * @ param args */public void convertListMapToTree (List
      
        > ListMaps, String... args) {Object value = null; String path = ""; Node pNode = null; Node node = null; Map
       
         NodeValue = new HashMap
        
          (); NodeList. add (rootNode); for (Map
         
           Map: listMaps) {path = ""; pNode = getRoot (); for (int I = 0; I <args. length; I ++) {String key = args [I]; value = map. get (key); path + = "/" + value; node = findNodeByPath (path); if (node = null) {node = new Node (IdGenerator. uuidGenerator (), pNode. getId (), String. valueOf (value), path); if (I = args. length-1) {nodeValue = map;} else {nodeValue = getNodeValueByPath (path, args);} node. setNodeValue (nodeValue); nodeList. add (node) ;}else {pNode = node ;}}}/*** according to the node path node, nodeValue * nodeValue should contain the Text of the parent node, instead of containing the text of the child node, the leaf node should contain all values * @ param path * @ param args * @ return */private Map
          
            GetNodeValueByPath (String path, String [] args) {Map
           
             NodeValue = new HashMap
            
              (); String [] values = path. split ("/"); for (int I = 1; I <values. length; I ++) {nodeValue. put (args [I-1], values [I]);} return nodeValue;} public Node getRoot () {return rootNode ;} /*** all subnodes of a node * @ param pNode * @ return */public List
             
               GetChildNodes (Node pNode) {List
              
                ChildNodes = new ArrayList
               
                 (); If (pNode = null | pNode. getId () = null) {return childNodes;} for (Node node: nodeList) {if (pNode. getId (). equals (node. getpId () {childNodes. add (node) ;}} return childNodes;}/*** check whether a node exists based on the path (because the path is unique) * @ param path * @ return: Find the node and return it, otherwise, null */public Node findNodeByPath (String path) {for (Node node: nodeList) {if (path. equals (node. getPath () {return node;} return null ;} /*** perform recursive depth traversal from a Node * @ param pNode */public void recursionTraversal (Node pNode) {List
                
                  ChildNodes = getChildNodes (pNode); for (Node node: childNodes) {System. out. println (node. toString (); if (getChildNodes (node ). size ()> 0) {recursionTraversal (node );}}}}
                
               
              
             
            
           
          
         
        
       
      
     
    
   
  
 

The core method is convertListMapToTree, which is the field name of the data source and node.

Call method:

Tree. convertListMapToTree (listMaps, "COUNTRY", "PROVINCE", "CITY", "STREET ");

Execution result:

//China/China/HeBei/China/HeBei/BaoDing/China/HeBei/BaoDing/street1/China/HeBei/HengShui/China/HeBei/HengShui/street1/China/ShanDong/China/ShanDong/Jian/China/ShanDong/Jian/street1/China/ShanDong/QingDao/China/ShanDong/QingDao/street1/China/ShanDong/YanTai/China/ShanDong/YanTai/street1/Japan/Japan/JiuZhou/Japan/JiuZhou/ChangQi/Japan/JiuZhou/ChangQi/street2/America/America/California/America/California/Los Angeles/America/California/Los Angeles/street3/England/England/Norwich/England/Norwich/Any/England/Norwich/Any/street4


Note the following points:

1. The order in which field name parameters are transmitted is the hierarchical order of nodes, from high to low. If an error is written, the result is inaccurate.

2. There must be a root node, which is essential for the tree structure. The default root node has been provided in the program and a custom interface has also been provided.

3. In this program, nodeValue only contains the field values from the current node to the root node (except for the leaf node). The leaf node contains all the field values, for example, in this example, the leaf node also contains data such as ID = 1, although it is not applied to the node level.

4. Determining whether a path exists is a key step. If this step is not accurate, the entire program will end with a failure.

Disadvantages:

Global Search is available in many places, which is inefficient and is expected to be improved in the future.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.