How to hide an Enum Value in Java?

Asked by At

I have a Enum class with rights.

public enum UserRight {
    SYSTEMMANAGEMENT, USERADMINISTRATION, ROLEADMINISTRATION, 
    STRUCTUREADMINISTRATION, DOCUMENTADMINISTRATION;
}

Now i want to load all my rights into a list except SYSTEMMANAGEMENT. I do it now like this:

availrightslist.addAll(Arrays.asList(UserRight.values()));

How can I load all rights without the SYSTEMMANAGEMENT right?

4 Answers

13
Lino On Best Solutions

You can just remove it after you've added all:

availrightslist.remove(UserRight.SYSTEMMANAGEMENT);

Or use some EnumSet magic:

Set<UserRight> rights = EnumSet.complementOf(EnumSet.of(UserRight.SYSTEMMANAGEMENT));

Generally if you have a Collection of enums it is recommended to use an EnumSet. Because having a UserRight two times doesn't really make sense.

2
cmoetzing On

You can simply remove your unwanted right.

Collections.addAll(availrightslist, UserRight.values())
availrightslist.remove(UserRight.SYSTEMMANAGEMENT);

Or you just add what you need.

for(UserRight right : UserRight.values()) {
    if(right != UserRight.SYSTEMMANAGEMENT)
        availrightslist.add(right);
}
1
ChocolateAndCheese On

There is no build in support for hiding an enum value, you have to manually filter it out:

List<UserRight> okRights = Arrays.stream(UserRights.values())
    .filter(userRight -> userRight != UserRight.SYSTEMMANAGEMENT)
    .collect(Collectors.toList());
availablerightslist.addall(okRights);
-1
Community On

you can try this I am not sure whether it's a optimal solution or not.

Arrays.asList(UserRight.values())
      .stream()
      .filter(value-> value != UserRight.SYSTEMMANAGEMENT)
      .collect(Collectors.toList())