hotmeatballsoup
hotmeatballsoup

Reputation: 605

Checking list of enums with Java 8 Stream API

Java 8 here. I have the following classes:

public enum Role {
  Admin,
  FunUser,
  SeriousUser,
  ...
  BasicUser;
}

@Getter
@Setter
public class User {
  private String login;
  private List<Role> roles;
  ...
}

I'd like to write some code using the Stream API that checks for whether the current user is an "Admin" or a "SeriousUser".

My best attempt thus far, which works, is still not Java 8ish:

if (user.getRoles().contains(Role.Admin) || user.getRoles().contains(Role.SeriousUser)) {
  ...
}

Is there a way to perform this enum check for several "cherry picked" roles via the Java 8 Stream API?

Upvotes: 2

Views: 281

Answers (2)

lczapski
lczapski

Reputation: 4120

Other option:

if(Stream.of(Role.Admin, Role.SeriousUser).anyMatch(user.getRoles()::contains)){
  ...
}

Upvotes: 4

Hadi
Hadi

Reputation: 17289

You can do like this:

if( user.getRoles().stream()
         .anyMatch(role -> role.equals(Role.Admin) || role.equals(Role.SeriousUser))){
   ...
}

Upvotes: 1

Related Questions