Andrey Popov
Andrey Popov

Reputation: 115

Search in Set collections

I have a Role object in which there is a set of Rolenames, I want to make a check on whether the user has a particular role. Tell me how best to do it to be beautiful and concise.

Role.java

@Table(name = "roles")
public class Role {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Enumerated(EnumType.STRING)
    @NaturalId
    @Column(length = 60)
    private RoleName name;

RoleName.java:

public enum RoleName {
    ROLE_ADMIN,
    ROLE_MANAGER,
    ROLE_CLIENT,
    ROLE_USER,
}

Now my search looks like this:

boolean isFind = false;
        for (Role role : user.getRoles()) {
            isFind = role.getName().equals(RoleName.ROLE_CLIENT);
            if (isFind) break;
        }

But I do not really like this way. Can you suggest a better option?

Upvotes: 1

Views: 111

Answers (1)

davidxxx
davidxxx

Reputation: 131556

You could use stream such as :

boolean isFind = 
    user.getRoles()
        .stream()
        .map(Role::getName)
        .anyMatch(n -> n == RoleName.ROLE_CLIENT);

Upvotes: 2

Related Questions