I have an enum :
public enum PermissionsEnum {
ABC("Abc"),
XYZ("Xyz"),
....
}
And then I have a list of Enums. I want to check if my list has at least one of the enums. I currently check it by an iterative approach. I also know there is a way to do it by using ||
checking list.contains(enum.ABC..) || list.contains(enum.XYZ) || ...
.
Is there a better way to do it?
This question shows how to do it if the objective list is a list of Strings, I want to get the matching status if the list is another list of enums.
Collections.disjoint
returns true
if the two specified collections have no elements in common. If it returns false
, then your list has at least one of the enums.
boolean contains = !Collections.disjoint(list, EnumSet.allOf(PermissionsEnum.class)));
A Stream API approach could be:
EnumSet<PermissionsEnum> set = EnumSet.allOf(PermissionsEnum.class);
boolean contains = list.stream().anyMatch(set::contains);
(similar to an iterative approach but with parallelisation included)
You can use Collections.disjoint()
.
Create another List with the enums you want to check and then do
Collections.disjoint(list, listOfEnumsToCheck)
. It returns true if no elements are found. If it is false at least one element is present.
I guess you can even use Enum.values() so it will become:
// Using ! to show there is at least one value
if (!Collections.disjoint(list, PermissionsEnum.values()) {
doStuff
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With