Implement comparable interface to sort tree structure data

Source: Internet
Author: User

Background:

The unordered data in the database is output as a tree structure,


Each record corresponds to a database of data,

Requirements come, then how to achieve, first of all, the simplest is directly from the database in order to detect, and then print,

Simply put, the Oracle database has the corresponding statement can be implemented, it is easy, but SQL Server did not, try to under no success,

Consider the compatibility of the database, just like the data in the background to sort,

Well, this is what this Wen said, sort of. The sorting rules are clear.

。。。 Cut......

Just started to say that only need 3 levels of scaling, that is, each node under a maximum of only two nodes, that good, directly in

CompareTo write Dept.getparnt (). GetParent () so judged,

After a period of time and said to the level 4 structure .... Messy... I'm going to rewrite this method again,

Now write a generic, no matter how many levels can be


CompareTo method:

@Override public int CompareTo (Dept d) {if (This.getrootparent (). GetId (). Intvalue ()! = D.getrootparent (). GetId (). In TValue ()) {//does not have the same parent, then under different root nodes, sort by order of the root node if (This.getrootparent (). GetOrder () > D.getrootparent (). Getord    ER ()) {return 1;    }else if (This.getrootparent (). GetOrder () < D.getrootparent (). GetOrder ()) {return-1; }}else{//Under the same root node if (Issamebranchatabranch (d)! = NULL) {//On one line if (This.getid (). Intvalue () = = Issame    Branchatabranch (d). GetId (). Intvalue ()) {return-1;    }else{return 1;    }}else{Dept Togetherparentfirst = Havesameparentsbutbotabranch (d); if (This.getparent (). GetId (). Intvalue () = = Togetherparentfirst.getid (). Intvalue ()//both Level 2 && d.getparent (). GetId (). Intvalue () = = Togetherparentfirst.getid (). Intvalue ()) {if (This.getorder (). Intvalue () > D.getorder ().    Intvalue ()) {return-1;    }else if (This.getorder (). Intvalue () < D.getorder (). Intvalue ()) {return 1; }else{   return 0;    }} Dept temp = this;    int orderthis = 0;    int orderd = 0; while (temp.getparent () = null) {if (Temp.getid (). Intvalue () = = Togetherparentfirst.getid (). Intvalue ()) {orderthis =    Temp.getorder ();    }else{temp = temp.getparent ();    }} temp = D; while (temp.getparent () = null) {if (Temp.getid (). Intvalue () = = Togetherparentfirst.getid (). Intvalue ()) {orderd = tem    P.getorder ();    }else{temp = temp.getparent ();    }} if (Orderthis > Orderd) {return-1;    }else if (Orderthis < orderd) {return 1;            }}} return 0; }


Complete test Code:

The printing results are as follows:

Package Test;import Java.util.arraylist;import Java.util.collections;import java.util.list;public class Jtest{static arraylist<dept> deptlist = new arraylist<dept> (); Static{initdata ();}    /** * Main program entry * @param args */public static void main (string[] args) {print ("= = = should order = = =");    Iteratorprintdeptlist (deptlist);//Printing print ("= = = = = = = = = = = = =");        Radomswaplist (deptlist);    Iteratorprintdeptlist (deptlist);//Print Collections.sort (deptlist);//Sort print ("= = = = = = = = = = = = = = = = = = = Iteratorprintdeptlistwithlevel (deptlist);//print}//Initialize test data private static void InitData () {Jtest Jtest = new J Test ();//This is written as an internal class because at that time wanted to do another test, ignoring Dept deptlevel01_1 = Jtest.new Dept (1, "Level01_deptlevel01_1", 5, Null,null);D ept Deptlevel01_2 = Jtest.new Dept (2, "Level01_deptlevel01_2", 4, Null,null);D ept deptlevel01_3 = Jtest.new Dept (3, "level01_ Deptlevel01_3 ", 3, Null,null);D ept deptlevel01_4 = Jtest.new Dept (4," Level01_deptlevel01_4 ", 5, Null,null);D ept Deptlevel02_1 = Jtest.new DePT (5, "Level02_deptlevel02_1", 9, 1,deptlevel01_1);D ept deptlevel02_2 = jtest.new Dept (6, "Level02_deptlevel02_2", 5, 1, deptlevel01_1);D ept deptlevel02_3 = jtest.new Dept (7, "Level02_deptlevel02_3", 6, 1,deptlevel01_1);D ept deptlevel02_4 = Jtest.new Dept (8, "Level02_deptlevel02_4", 6, 2,deptlevel01_2);D ept deptlevel02_5 = jtest.new Dept (9, "level02_ Deptlevel02_5 ", 6, 3,deptlevel01_3);D ept deptlevel02_6 = jtest.new Dept (" Level02_deptlevel02_6 ", 8, 3,deptlevel01_3 );D ept deptlevel03_1 = Jtest.new Dept (one, "Level03_deptlevel03_1", 6, 8,deptlevel02_4);D ept deptlevel03_2 = jtest.new Dep T ("Level03_deptlevel03_2", 8, 8,deptlevel02_4);D ept deptlevel03_3 = jtest.new Dept ("Level03_deptlevel03_3", 6, 5 , deptlevel02_1);D ept deptlevel03_4 = jtest.new Dept ("Level03_deptlevel03_4", 8, 5,deptlevel02_1);d Eptlist.add ( deptlevel01_3);d Eptlist.add (deptlevel02_5);d eptlist.add (deptlevel02_6);d eptlist.add (deptlevel01_1); Deptlist.add (deptlevel02_3);d eptlist.add (deptlevel02_2);d Eptlist.add (DeptlevEl02_1);d Eptlist.add (deptlevel03_3);d eptlist.add (deptlevel03_4);d eptlist.add (deptlevel01_2);d Eptlist.add (    Deptlevel02_4);d Eptlist.add (deptlevel03_1);d eptlist.add (deptlevel03_2);d eptlist.add (deptlevel01_4);} /** * Scrambled List order * @param deptlist */static void radomswaplist (list<dept> deptlist) {int size = Deptlist.size (); for (in t i = 0; I < 30; i++) {int randomnum = (int) (Math.random () *10), if (randomnum >= size) {continue;} Dept temp = deptlist.get (randomnum);d eptlist.set (Randomnum, Deptlist.get (Size-1-Randomnum));d eptlist.set (Size-1-Ra Ndomnum, temp);}} /** * Traverse Print ArrayList * @param deptlist */static void iteratorprintdeptlist (list<dept> deptlist) {for (Dept DEPT:DEPTL IST) {System.out.println ("DeptID:" + "" +dept.getid () + "," + dept.getname () + "," + Dept.getparentid ());} Print ();} /** * Traverse print ArrayList (indent by level) * @param deptlist */static void Iteratorprintdeptlistwithlevel (list<dept> deptlist) { for (Dept dept:deptlist) {Int. level = Dept.getlevel (), for (int i= 1; i< lEvel; i++) {System.out.print ("--");} System.out.println ("DeptID:" + "" +dept.getid () + "," + dept.getname () + "," + Dept.getparentid ());} Print ();} /** * Traverse Print ArrayList * @param deptlist */static void simpleiteratorprintdeptlist (list<dept> deptlist) {for (Dept Dept : deptlist) {System.out.print (Dept.getid () + ",");} System.out.println ();} static void print () {System.err.println ("------------------------");}          static void print (String str) {System.err.println (str);}    Class Dept implements comparable<dept>{private Integer ID;    private String name;    private Integer order;        Private Integer ParentID;        Private Dept parent;    /** * Gets the current department is the first level of department, the parent is NULL for 1 levels, has a parent of level 2, and so on. */private int getlevel () {int temp = 1;    Dept tempdept = this;    while (tempdept.getparent () = null) {tempdept = Tempdept.getparent ();    temp = temp +1;    } return temp; } private Dept sameparents (Dept d) {Dept Temp1 = this;while (Temp1! = null) {DeptTemp2 = D;while (Temp2! = null) {if (Temp1.getid () = = Temp2.getid ()) {return temp1;} Temp2 = Temp2.getparent ();} Temp1 = Temp1.getparent ();}        return null;    /** * Gets the parent of the root node * @return */private Dept getrootparent () {if (this.getparent () = = null) {    return this;    }else{Dept tmp = this;        while (tmp.getparent () = null) {TMP = Tmp.getparent ();    } return TMP;         }}/** * Gets the parent * @param level * @return */private Dept getParent (int level) of a level {    int thislevel = This.getlevel ();    Dept depttemp = this;    while (depttemp.getparent () = null) {thislevel = ThisLevel-1;    Depttemp = Depttemp.getparent ();    if (level = = Thislevel) {return depttemp;    }} return null; } @Override public int compareTo (Dept d) {if (This.getrootparent (). GetId (). Intvalue ()! = D.getrootparent (). g Etid (). Intvalue ()) {//does not have the same parent, then under different root nodes, sort by the order of the root node if (This.getrootparent (). GetOrder () > D.getrootparent (). GetOrder ()) {return 1;    }else if (This.getrootparent (). GetOrder () < D.getrootparent (). GetOrder ()) {return-1; }}else{//Under the same root node if (Issamebranchatabranch (d)! = NULL) {//On one line if (This.getid (). Intvalue () = = Issame    Branchatabranch (d). GetId (). Intvalue ()) {return-1;    }else{return 1;    }}else{Dept Togetherparentfirst = Havesameparentsbutbotabranch (d); if (This.getparent (). GetId (). Intvalue () = = Togetherparentfirst.getid (). Intvalue ()//both Level 2 && d.getparent (). GetId (). Intvalue () = = Togetherparentfirst.getid (). Intvalue ()) {if (This.getorder (). Intvalue () > D.getorder ().    Intvalue ()) {return-1;    }else if (This.getorder (). Intvalue () < D.getorder (). Intvalue ()) {return 1;    }else{return 0;    }} Dept temp = this;    int orderthis = 0;    int orderd = 0; while (temp.getparent () = null) {if (Temp.getid (). Intvalue () = = Togetherparentfirst.getid (). Intvalue ()) {orderthis = TeMp.getorder ();    }else{temp = temp.getparent ();    }} temp = D; while (temp.getparent () = null) {if (Temp.getid (). Intvalue () = = Togetherparentfirst.getid (). Intvalue ()) {orderd = tem    P.getorder ();    }else{temp = temp.getparent ();    }} if (Orderthis > Orderd) {return-1;    }else if (Orderthis < orderd) {return 1;            }}} return 0; }/** * Determines if two nodes have a common parent node (1) (and two nodes are on one branch, that is, one node is the parent node of another node) * @param d the node to compare to the current node * @return returns the parent node (this parent node is its    A node in) */private Dept Issamebranchatabranch (Dept d) {Dept temp = this;    while (temp.getparent () = null) {if (Temp.getparent (). GetId (). Intvalue () = = D.getid ()) {return D;    } temp = Temp.getparent ();    } temp = D;    while (temp.getparent () = null) {if (Temp.getparent (). GetId (). Intvalue () = = This.getid ()) {return this;    } temp = Temp.getparent ();    } return null; }/** * Determine if there is the same parent node (2) (two nodes are not in different small branches, this node is not any one of themnode, which is the case of removing 1) * @param d * @return */private Dept Havesameparentsbutbotabranch (Dept d) {Dept temp =    This    while (temp.getparent () = null) {if (Temp.getparent (). Issamebranchatabranch (d)! = null) {return temp.getparent ();    } temp = Temp.getparent ();    } return null; } @Override Public String toString () {return This.getid () + "," +this.getparent (). Getparentid () + "," +this.getn    Ame ();     }/** * constructor * @param ID * @param name * @param order * @param parentid * @param parent    */public Dept (integer ID, String name, integer order, integer parentid,dept parent) {super ();    This.id = ID;    THIS.name = name;    This.order = order;    This.parentid = ParentID;    This.parent = parent;    } public Integer GetId () {return id;    } public void SetId (Integer id) {this.id = ID;    } public String GetName () {return name;   } public void SetName (String name) {this.name = name; } public Integer GetOrder () {return order;    public void Setorder (Integer order) {this.order = order;    } public Dept GetParent () {return parent;    } public void SetParent (Dept parent) {this.parent = parent;    } public Integer Getparentid () {return parentid;    } public void Setparentid (Integer parentid) {this.parentid = ParentID; }    }}





Implement comparable interface to sort tree structure data

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.