list构建数据库父子关系
递归解决父子表伪代码
@Override
public List getAll() {
//数据库中获取所有的数据
List consumablesDOS = BeanUtils.deepClone(generalBeanService.queryList(new ConsumablesDO()),ConsumablesDTO.class);
//默认根是0
ConsumablesDTO head = new ConsumablesDTO(0);
return getNode(consumablesDOS,head);
}
private List getNode(List list, ConsumablesDTO node){
List dtoList = list.stream().filter(a -> node.getId().equals(a.getParentId())).collect(Collectors.toList());
if (CollectionUtils.isEmpty(dtoList)) return Collections.emptyList();
dtoList.forEach(dto -> dto.setConsumablesParentDTOS(getNode(list,dto)));
return dtoList;
}
for循环list建立树形图伪代码
public List listToTree1() {
List list = list();
List tree = new ArrayList<>();
for (User user : list) {
//找到根节点
if (user.getParentId() == null || user.getParentId().equals(0L)) {
tree.add(user);
}
List children = new ArrayList<>();
//再次遍历list,找到user的子节点
for (User node : list) {
if (node.getParentId().equals(user.getId())) {
children.add(node);
}
}
user.setChildren(children);
}
return tree;
}
for循环list建立树形图(MAP)伪代码
//首先将获取到的List数据转换为Map集合
List userList=new ArrayList<>();
Map map = userList.stream().collect(Collectors.toMap(User::getId,User->User));
//便利集合,进行匹配
map.forEach((k,v)->{
//如果根据pid能改查询到对应对象,证明存在父级,将该对象add进子级集合
User user = map.get(v.getPid());
if(user!=null){
user.getChildren().add(user);
}
});