java递归遍历树结构目录
目录实体
private int id; private int pid; private String name;
递归遍历方法
private void getTree(Menu menu ,List<Menu> menus){ int pid = menu.getId(); List<Menu> childs = null; Iterator<Menu> iterator = menus.iterator(); while (iterator.hasNext()) { Menu m = iterator.next(); if(m.getPid() == pid){ childs = menu.getChild(); if(childs == null) childs = new ArrayList<Menu>(); childs.add(m); iterator.remove(); menu.setChild(childs); } } if(childs != null && !childs.isEmpty() && menus !=null && !menus.isEmpty()){ Iterator<Menu> iterator2 = childs.iterator(); while(iterator2.hasNext()){ Menu next = iterator2.next(); getTree(next,menus); } } }
------lamda语法------
@Data public class LabelVO implements Serializable { private static final long serialVersionUID = 1L; /** * ID */ private Long id; /** * 父ID */ private Long pId; /** * 标签名 */ private String labelName; /** * 标签值 */ private String labelValue; /** * 标签类别 */ private String labelType; /** * 排序 */ private Integer sort; /** * 子标签 */ private List<LabelVO> children; }
public List<LabelVO> labelList(String labelType) { LabelVO labelVO = redisService.getCacheObject(MDA.CACHE_LABEL + labelType); if (labelVO != null && StringUtils.isNotEmpty(labelVO.getChildren())) { return labelVO.getChildren(); } List<Label> labels = labelMapper.selectList(new LambdaQueryWrapper<Label>().eq(Label::getLabelType, labelType).eq(Label::getIsDelete, MDA.STRING_0)); LabelVO rootVO = new LabelVO(); rootVO.setId(0L); buildTree(rootVO, labels); redisService.setCacheObject(MDA.CACHE_LABEL + labelType, rootVO, CacheConstants.EXPIRATION, TimeUnit.MINUTES); return rootVO.getChildren(); }
private void buildTree(LabelVO labelVO, List<Label> labels) {
Long pid = labelVO.getId();
List<LabelVO> childs = labelVO.getChildren();
if (childs == null) {
childs = new ArrayList<>();
}
Iterator<Label> iterator = labels.iterator();
while (iterator.hasNext()) {
Label m = iterator.next();
if (pid.equals(m.getpId())) {
LabelVO l = FileConvert.INSTANCE.toVO(m);
l.setName(l.getLabelName());
l.setValue(l.getLabelValue());
childs.add(l);
iterator.remove();
}
}
//排序
if(StringUtils.isNotEmpty(childs)){
childs = childs.stream().sorted(Comparator.comparingInt(LabelVO::getSort)).collect(Collectors.toList());
labelVO.setChildren(childs);
if (StringUtils.isNotEmpty(labels)) {
for (LabelVO next : childs) {
buildTree(next, labels);
}
}
}
}
----------------------------------------------------------------------------------------邪恶的分隔线-------------------------------------------------------------------------------------------------
这是凑字数这是凑字数这是凑字数这是凑字数这是凑字数这是凑字数这是凑字数这是凑字数这是凑字数这是凑字数这是凑字数这是凑字数这是凑字数这是凑字数这是凑字数这是凑字数这是凑字数这是凑字数这是凑字数这是凑字数这是凑字数这是凑字数这是凑字数这是凑字数这是凑字数这是凑字数这是凑字数这是凑字数这是凑字数这是凑字数这是凑字数这是凑字数