Search code examples
javagenericsnested-loops

Iterating through lists of list in java


I have two tables User and Roles with one-to-one relation as below.

User
_________________________________________
| Id  | user_name | full_name | creator |
_________________________________________
| 1   | a         | A         | a       |
| 2   | b         | B         | a       |
| 3   | c         | C         | a       |
| 4   | d         | D         | c       |
| 5   | e         | E         | c       |
| 6   | f         | F         | e       |
| 7   | g         | G         | e       |
| 8   | h         | H         | e       |
| 9   | i         | I         | e       |
|10   | j         | J         | i       |
_________________________________________

Roles
_______________________________________
| id | user_mgmt | others | user_id |
_______________________________________
| 1  | 1        | 1      | 1           |
| 2  | 0        | 1      | 2           |
| 3  | 1        | 0      | 3           |
| 4  | 0        | 1      | 4           |
| 5  | 1        | 1      | 5           |
| 6  | 0        | 1      | 6           |
| 7  | 0        | 0      | 7           |
| 8  | 0        | 0      | 8           |
| 9  | 1        | 0      | 9           |
________________________________________

The Roles table have boolean columns, so if an User have user_mgmt role he can add many users (How many users can be added by an user is not definite). I want to fetch all users created by an user and his child users ( a is parent, c is child of a and e is child of c ..) .

Here is my code to fetch users

public void loadUsers(){
  List<Users> users = new ArrayList<>();

  String creator = user.getUserName();
  List<Users> createdUsers = userService.getUsersByCreator(creator);
  for(Users user : createdUsers) {
    Roles role = createdUsers.getRoles();
    if(role.isEmpMgnt()){
      users.add(user);
      loadUsers();
    }
  }
}

This gives me an stack overflow error. If i don't call loadUsers() recursively it returns only a single child result. So is there any solutions to this ? Thanks for any help in advance.


Solution

  • This gives you stack overflow error because a has creator a. So you have infinite loop for user a. For a you should set creator to null or skip self references in code. Also you should pass current user into loadUsers() method and read only users that are created by it. Like

    public void loadUsers(String creator)
    

    and only process users created by that creator. Here

    String creator = user.getUserName();
    

    what is user? You should use creator. Question is how do you obtain initial creator. Probably initial creator should be user where creator is null.