Java creates the tree structure algorithm instance code
- 2020-06-01 09:39:38
- OfStack
In the relevant development of JavaWeb, the display of multi-level menus is often involved. In order to facilitate the management of menus, database is needed to support them. In this case, relevant algorithm is adopted to assemble and sort bar records in the database and assemble menus into a tree structure.
The first is the required JavaBean
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
/**
* <Description> Menu extension <br>
*/
public class MenuExt implements Serializable {
/**
* The menu ID
*/
private Long id;
/**
* The name of the menu
*/
private String name;
/**
* Address of the menu
*/
private String url;
/**
* The menu icon
*/
private String icon;
/**
* The parent menu ID
*/
private Long parentId;
/**
* Sub menu
*/
private List<MenuExt> children = new ArrayList<MenuExt>();
/**
* The menu sequence
*/
private Integer ordby;
/**
* State of the menu
*/
private String state;
// omit Getter and Setter
/**
*
* <Description> Child node sorting <br>
*
*/
public void sortChildren() {
Collections.sort(children, new Comparator<MenuExt>() {
@Override
public int compare(MenuExt menu1, MenuExt menu2) {
int result = 0;
Integer ordby1 = menu1.getOrdby();
Integer ordby2 = menu2.getOrdby();
Long id1 = menu1.getId();
Long id2 = menu2.getId();
if (null != ordby1 && null != ordby2) {
result = (ordby1 < ordby2 ? -1 : (ordby1 == ordby2 ? 0 : 1));
} else {
result = (id1 < id2 ? -1 : (id1 == id2 ? 0 : 1));
}
return result;
}
});
// For each node down 1 Layer nodes are sorted
for (Iterator<MenuExt> it = children.iterator(); it.hasNext();) {
it.next().sortChildren();
}
}
public List<MenuExt> getChildren() {
return children;
}
public void setChildren(List<MenuExt> children) {
this.children = children;
}
}
Java algorithm
public static List<MenuExt> createTreeMenus(List<MenuExt> menus) {
List<MenuExt> treeMenus = null;
if (null != menus && !menus.isEmpty()) {
// Create the root node
MenuExt root = new MenuExt();
root.setName(" Menu root ");
// The assembly Map data
Map<Long, MenuExt> dataMap = new HashMap<Long, MenuExt>();
for (MenuExt menu : menus) {
dataMap.put(menu.getId(), menu);
}
// Assemble the tree structure
Set<Entry<Long, MenuExt>> entrySet = dataMap.entrySet();
for (Entry<Long, MenuExt> entry : entrySet) {
MenuExt menu = entry.getValue();
if (null == menu.getParentId() || 0 == menu.getParentId()) {
root.getChildren().add(menu);
} else {
dataMap.get(menu.getParentId()).getChildren().add(menu);
}
}
// Let's do it with the tree 2 Tree sort
root.sortChildren();
treeMenus = root.getChildren();
}
return treeMenus;
}