在JavaWeb的相關(guān)開發(fā)中經(jīng)常會涉及到多級菜單的展示,為了方便菜單的管理需要使用數(shù)據(jù)庫進行支持,本例采用相關(guān)算法講數(shù)據(jù)庫中的條形記錄進行相關(guān)組裝和排序講菜單組裝成樹形結(jié)構(gòu)。
首先是需要的JavaBean
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
|
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> 菜單擴展<br> */ public class MenuExt implements Serializable { /** * 菜單ID */ private Long id; /** * 菜單名稱 */ private String name; /** * 菜單地址 */ private String url; /** * 菜單圖標 */ private String icon; /** * 父菜單ID */ private Long parentId; /** * 子菜單 */ private List<MenuExt> children = new ArrayList<MenuExt>(); /** * 菜單順序 */ private Integer ordby; /** * 菜單狀態(tài) */ private String state; //省略Getter和Setter /** * * <Description> 孩子節(jié)點排序<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; } }); // 對每個節(jié)點的下一層節(jié)點進行排序 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算法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
public static List<MenuExt> createTreeMenus(List<MenuExt> menus) { List<MenuExt> treeMenus = null ; if ( null != menus && !menus.isEmpty()) { // 創(chuàng)建根節(jié)點 MenuExt root = new MenuExt(); root.setName( "菜單根目錄" ); // 組裝Map數(shù)據(jù) Map<Long, MenuExt> dataMap = new HashMap<Long, MenuExt>(); for (MenuExt menu : menus) { dataMap.put(menu.getId(), menu); } // 組裝樹形結(jié)構(gòu) 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); } } // 對樹形結(jié)構(gòu)進行二叉樹排序 root.sortChildren(); treeMenus = root.getChildren(); } return treeMenus; } |
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:http://www.cnblogs.com/banning/p/6218633.html