The best way to check if a list contains at least one of the enumerations

I have an enumeration:

public enum PermissionsEnum {
    ABC("Abc"),        
    XYZ("Xyz"),
    ....
}

And then I have a list of strings. I want to check if at least one of the enumerations is on my list. I am currently testing it using an iterative approach. I also know that there is a way to do this using ||validation list.contains(enum.ABC..) || list.contains(enum.XYZ) || ....

Is there a better way to do this?

+5
source share
2 answers

List<String>never contains meaning PermissionsEnum.

The condition list.contains(enum.ABC) || list.contains(enum.XYZ)will not work.

Instead, you can map PermissionsEnum.values()to Stream<String>and call Stream#anyMatchon it:

boolean result = Arrays.stream(PermissionsEnum.values())
                       .map(PermissionsEnum::getValue)
                       .anyMatch(list::contains);

* I assumed that the constructor parameter is accessible by the method getValue.


, ( ), :

Set<String> values = Arrays.stream(PermissionsEnum.values())
                           .map(PermissionsEnum::getValue)
                           .collect(Collectors.toSet());

boolean result = list.stream().anyMatch(values::contains);
+5

for.

boolean contains = false;
for (PermissionsEnum permission : PermissionsEnum.values()) {
    if (list.contains(permission.getName())) {
        contains = true;
        break;
    }
}

Collections.disjoint() :

Set<String> permissionsNames = Stream.of(PermissionsEnum.values())
                                     .map(PermissionsEnum::getName())
                                     .collect(Collectors.toSet());

boolean contains = !Collections.disjoint(list, permissionsNames);

PS: getName() .

+4

Source: https://habr.com/ru/post/1696005/


All Articles