I have a solution with EnumSet. However, this is too verbose, and I suppose I prefer @Peter Lawrey's solution.
Effective Java by Bloch recommends using EnumSet over bit fields, but I would make an exception here. However, I posted my solution because it might be useful for someone with a slightly different problem.
import java.util.EnumSet; public enum MatchingRegex { Tall, Blue, Hairy; public static EnumSet<MatchingRegex> findValidConditions(String stringToMatch) { EnumSet<MatchingRegex> validConditions = EnumSet.noneOf(MatchingRegex.class); if (... check regex stringToMatch for Tall) validConditions.add(Tall); if (... check regex stringToMatch for Blue) validConditions.add(Blue); if (... check regex stringToMatch for Hairy) validConditions.add(Hairy); return validConditions; } }
and you use it as follows:
Set<MatchingRegex> validConditions = MatchingRegex.findValidConditions(stringToMatch); if (validConditions.equals(EnumSet.of(MatchingRegex.Tall, MathchingRegex.Blue, MatchingRegex.Hairy)) ... else if (validConditions.equals(EnumSet.of(MatchingRegex.Tall, MathchingRegex.Blue)) ... else if ... all 8 conditions like this
But that would be more efficient:
if (validConditions.contains(MatchingRegex.Tall)) { if (validConditions.contains(MatchingRegex.Blue)) { if (validConditions.contains(MatchingRegex.Hairy)) ... // tall blue hairy else ... // tall blue (not hairy) } else { if (validConditions.contains(MatchingRegex.Hairy)) ... // tall (not blue) hairy else ... // tall (not blue) (not hairy) } else { ... remaining 4 conditions }
toto2
source share