java8 实现递归查询

1、实体类user

@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. 代码实现

/**
 * 实现递归
 *
 */
public HttpResponses<List<User>> getUser(){
  List<User> list = this.userService.list();
        //用map写法
        /*List 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;
    }

你可能感兴趣的:(java,java)