list构建数据库父子关系
递归解决父子表伪代码
@Override
public List<ConsumablesDTO> getAll() {
List<ConsumablesDTO> consumablesDOS = BeanUtils.deepClone(generalBeanService.queryList(new ConsumablesDO()),ConsumablesDTO.class);
ConsumablesDTO head = new ConsumablesDTO(0);
return getNode(consumablesDOS,head);
}
private List<ConsumablesDTO> getNode(List<ConsumablesDTO> list, ConsumablesDTO node){
List<ConsumablesDTO> 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<User> listToTree1() {
List<User> list = list();
List<User> tree = new ArrayList<>();
for (User user : list) {
if (user.getParentId() == null || user.getParentId().equals(0L)) {
tree.add(user);
}
List<User> children = new ArrayList<>();
for (User node : list) {
if (node.getParentId().equals(user.getId())) {
children.add(node);
}
}
user.setChildren(children);
}
return tree;
}
for循环list建立树形图(MAP)伪代码
List userList=new ArrayList<>();
Map<String,User> map = userList.stream().collect(Collectors.toMap(User::getId,User->User));
map.forEach((k,v)->{
User user = map.get(v.getPid());
if(user!=null){
user.getChildren().add(user);
}
});
|