Check if list contains at least one of another - enums

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 
} 

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)


If you can use java-8.

Arrays.stream(PermissionsEnum.values()).anyMatch(list::contains);

Enum#values()

Returns an array containing the constants of this enum type.

So we just need to wrap it into a stream and check if list contains any values. Important thing to remember is that

anyMatch not evaluate the predicate on all elements if not necessary for determining the result.

In other words it may return true as soon as element which satisfies predicate is found.

Apparently, more efficient way is to use EnumSet.allOf(PermissionsEnum.class)::contains because EnumSet.contains is much more efficient than List.contains:

list.stream().anyMatch(EnumSet.allOf(PermissionsEnum.class)::contains)

Tags:

Java

Enums

Java 8