介绍
本次利用Java中对象的引用来实现Java 对象列表转数组
代码
//将菜单列表根据parentId进行分组 key:parentId,value:List<Object>
Map<Long, List<MenuListDto>> collect = list.stream().filter(node -> StringUtils.isNotBlank(node.getParentId().toString())).collect(Collectors.groupingBy(node -> node.getParentId()));
//遍历菜单列表List,将Map中key=menu.getId()的值取出存入当前menu的children中
list.forEach(node -> node.setChildren(collect.get(node.getId())));
//list过滤掉非顶层分类的数据
List<MenuListDto> treeMenu = list.stream().filter(node -> node.getParentId() == 0).collect(Collectors.toList());
简单代码解释
/**
* @author huangqh
* @create 2020/11/16 14:04
* @Notes 注释
*/
@Data
@NoArgsConstructor
public class Node {
private int id;
private Node node;
public Node(int id){
this.id=id;
}
public static void main(String[] args) {
Node A = new Node(1);
Node B =new Node(2);
Node C =new Node(3);
A.setNode(B);
B.setNode(C);
//Node(id=1, node=Node(id=2, node=Node(id=3, node=null)))
System.out.println(A);
//Node(id=2, node=Node(id=3, node=null))
System.out.println(B);
//Node(id=3, node=null)
System.out.println(C);
}
}