1、实体类user
c
复制代码
@Data
@EqualsAndHashCode(callSuper = true)
@Accessors(chain = true)
@TableName("user")
public class User {
private Integer id;
private String parentId;
@TableField(exist = false)
private List<User> childList;
}
2. 代码实现
c
复制代码
/**
* 实现递归
*
*/
public HttpResponses<List<User>> getUser(){
List<User> list = this.userService.list();
//用map写法
/*List<User> listUser = list.stream().filter(user ->
user.getParentId().equals("0")).map(user -> {
user.setChildList(getChildrens(user,list));
return user;
}).collect(Collectors.toList());*/
//peek写法
List<User> listUser = list.stream().filter(user -> user.getParentId().equals("0"))
.peek(user ->
user.setChildList(getChildrens(user,list))).collect(Collectors.toList());
return success(listUser);
}
/**
* 代码实现递归方法
*
*/
public List<User> getChildrens(User user,List<User> userList){
List<User> childrens = userList.stream().filter(u -> Objects.equals(u.getParentId(),user.getId())).map(
u -> {
u.setChildList(getChildrens(u,userList));
return u;
}
).collect(Collectors.toList());
return childrens;
}