GoRobotFlame
GoRobotFlame

Reputation: 175

Filter list of objects by the value of sets of objects

I need to retrieve a list of users with a specific role. The user object contains a set of roles with id and role name as a String. Sample JSON with users:

[  
 {
    "id": "test-id-user2",
    "email": "[email protected]",
    "password": "$2a$04$JodczCrLPGYA1cCvtAWZoe47qhiBIMNjSexRFwCLevzRJQQSqZvaO",
    "firstName": "Test2",
    "lastName": "User2",
    "enabled": true,
    "confirmationToken": "0123token0123",
    "location": {
      "id": 1,
      "name": "West Vinewood"
    },
    "roles": [
      {
        "id": 1,
        "role": "ROLE_USER"
      }
    ]
  },
  {
    "id": "test-id-admin",
    "email": "[email protected]",
    "password": "$2a$04$Ll0WUAuU1p.sjqH.g.f03eHcfS8ox1Pen9tYk8/JdWlgfBr71nNO.",
    "firstName": "AdminTest",
    "lastName": null,
    "enabled": true,
    "confirmationToken": null,
    "location": null,
    "roles": [
      {
        "id": 2,
        "role": "ROLE_ADMIN"
      }
    ]
  }
]

I can achieve this by using if loop inside the for loop. A user has only one role (and for some reasons I have to use set for this):

List<User> member = new ArrayList<>();
for (User user : allUsers) {
    Set<UserRole> roles = user.getRoles();
    if (roles.iterator().next().getRole().equals("ROLE_USER")) {
        member.add(user);
    }
}

Is there is any other, easier way like lambda to filter set inside the list? I've tried this solution Java 8 lambda list inside list filter it filtering but it also duplicates the object.

Upvotes: 2

Views: 516

Answers (1)

Ousmane D.
Ousmane D.

Reputation: 56433

It could be done as follows using the stream API:

allUsers.stream()           
        .filter(u -> u.getRoles().iterator().next().getRole().equals("ROLE_USER"))
        .collect(Collectors.toCollection(ArrayList::new));

Upvotes: 1

Related Questions