I have an enum :
public enum PermissionsEnum {
ABC("Abc"),
XYZ("Xyz"),
....
}
And then I have a list of Strings. 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?
A List<String>
never contains a PermissionsEnum
value.
The condition list.contains(enum.ABC) || list.contains(enum.XYZ)
is not going to be working.
Instead, you could map PermissionsEnum.values()
to a Stream<String>
and call Stream#anyMatch
on it:
boolean result = Arrays.stream(PermissionsEnum.values())
.map(PermissionsEnum::getValue)
.anyMatch(list::contains);
*I assumed that constructor parameter is accessible by the getValue
method.
In case the list is large (a few iterations over it might take a lot of time) we could optimise the previous snippet a bit and iterate over the list once:
Set<String> values = Arrays.stream(PermissionsEnum.values())
.map(PermissionsEnum::getValue)
.collect(Collectors.toSet());
boolean result = list.stream().anyMatch(values::contains);