Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if list contains at least one of another - enums

Tags:

java

enums

java-8

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.

like image 827
S.Dan Avatar asked Apr 11 '18 10:04

S.Dan


2 Answers

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)

like image 187
Andrew Tobilko Avatar answered Sep 26 '22 05:09

Andrew Tobilko


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 
} 
like image 28
Veselin Davidov Avatar answered Sep 23 '22 05:09

Veselin Davidov