
说一下我们要达到的目的
有一个List<Menu>,其中Menu{id, parentId, children, value},全部Menu的ID都大于0,一层Menu的parentId=0。初始时全部Menu的children都为null,请写一个方法buildTree(List<Menu>), 创建一个Menu为root,将List<Menu>整理成树状结构。
我们都知道用以前for循环都可以实现,但是今夕是何年,都快2025年了是时候更新你的Java技术了,让代码子弹速度更快些,好,我们就利用steam流来实现吧
首先准备好菜单实体类(实际按照你们的需求来改动,这个例子只配好基本的属性)
/**
* 菜单实体类
*/
class Menu {
Integer id;
Integer parentId;
List<Menu> children;
String value;
public Menu(Integer id, Integer parentId, String value) {
this.id = id;
this.parentId = parentId;
this.children = null;
this.value = value;
}
}
核心递归树的方法
/***
* 递归生成树结构
* @param menus 菜单数据
*/
public static Menu buildTree(List<Menu> menus) {
//Function.identity() 返回 获取一个直接返回入参的函数。
Map<Integer, Menu> idMap = menus.stream().collect(Collectors.toMap(e -> e.id, Function.identity()));
idMap.put(0, new Menu(0, -1, "root"));
menus.stream().collect(Collectors.groupingBy(e -> e.parentId))
.entrySet().stream().forEach(entry -> {
idMap.get(entry.getKey()).children = entry.getValue();
});
return idMap.get(0);
}
再来检查结果的代码
/**
* 检查数据-打印树数据
* @param menu
* @param level 计算递归等级使用
*/
public static void printTree(Menu menu, int level) {
IntStream.range(0, level).forEach(i -> System.out.print("-"));
System.out.println(menu.value);
if (menu.children != null) {
menu.children.stream().forEach(c -> printTree(c, level+1));
}
}
然后我们测试测试这些方法
public static void main(String[] args) {
List<Menu> menus = Arrays.asList(
new Menu(1, 0, "Child 1"),
new Menu(2, 0, "Child 2"),
new Menu(4, 2, "Grandchild 2"),
new Menu(3, 1, "Grandchild 1"),
new Menu(6, 5, "Grandchild 2 son"),
new Menu(7, 5, "Grandchild 2 son"),
new Menu(5, 2, "Grandchild 3"),
new Menu(8, 7, "Grandchild 2 son son")
);
//构建树
Menu root = buildTree(menus);
//打印树
printTree(root, 0);
}
运行结果如下
root
-Child 1
--Grandchild 1
-Child 2
--Grandchild 2
--Grandchild 3
---Grandchild 2 son
---Grandchild 2 son
----Grandchild 2 son son
这个是不是你想要的结果呢,如果是,快点跟上大steam时代吧!!

459

被折叠的 条评论
为什么被折叠?



