Check if list contains at least one of another – enums

  • A+
Category:Languages

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)

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: