Read a lot of transfer scheme list tree at night, I feel not very good, this time to write a, put out of their own to share with
I felt very good, speak directly on the code
1, the type of object
@Data public class SystemAuth the implements the Serializable { / ** * permission id * / Private Integer the authid; / ** * parent permission id * / Private Integer parentId; / ** * set list sub permission id * / Private List <SystemAuth> Children ; }
When the object begins, only authid, as well as parentid, build tree after parentid will be a collection of child rights into all id list of the current authid, and so on.
2. Construction of the tree directly on the inside of the essence of the method
// query the database, check out the list needs a set of achievements the Set <SystemAuth> authIdsAndAuthType = systemAuthMapper.findAuths (); // create a list, hold all the top-most node List <SystemAuth> List = new new ArrayList <> (); // Create a map, used to store all nodes of the tree constructed, the parent node can easily find Final the HashMap <Integer, SystemAuth> = new new Map the HashMap <> (); // sort the data, in accordance with the parent sequence row id, priority guaranteed parent node process, according to the parent when the child check, always exist (essence) authIdsAndAuthType.stream () the sorted ((S1, S2) -> s1.getParentid () - s2.getParentid ()). .forEach (item- > { // the map into the current node, then the child node when the node can be found using well map.put (item.getAuthid () intValue (), Item.); // get the parent node of the current node, parentitem = map.get SystemAuth (item.getParentid () intValue ().); // there is a parent node if (parentitem = null!) { // erupted when the parent node list did not create, create the list IF (parentitem.getChildren () == null) { parentitem.setChildren (new new the ArrayList <SystemAuth> ()); } // put into the parent node of the node under parentitem.getChildren () the Add (Item);. } the else { // If there is no parent node, the node is put into the top-level node, as it has been sorted, you can ensure that if there is not, it must be top-level node. List.add (Item); } });
return List
Done, the present method uses a sorting cycle.
And, most importantly, list which is filled with objects, and map objects are installed with the same object, so that you can ensure that, when storing child nodes, the parent node in the list will be stored under the parent node synchronization look at the map , and the final return to list the root node, all objects are and OK it.
If you have any better options, you can give me a message Ha! ! ! !